Polymorphic association cho phép một model belongs_to nhiều model khác nhau qua cùng một association.
Ví dụ: Comment có thể thuộc về Post hoặc Video.
ruby
# Migration
create_table :comments do |t|
t.text :body
t.references :commentable, polymorphic: true # tạo commentable_id + commentable_type
end
# Models
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
end
class Post < ApplicationRecord
has_many :comments, as: :commentable
end
class Video < ApplicationRecord
has_many :comments, as: :commentable
end
# Query
post.comments # Comments với commentable_type="Post", commentable_id=post.id
video.comments # Comments với commentable_type="Video", commentable_id=video.idCột commentable_type lưu tên class, commentable_id lưu id.
Rails tự handle việc lọc.
A polymorphic association lets a model belongs_to multiple other models through a single association.
Example: Comment can belong to either Post or Video.
ruby
# Migration
create_table :comments do |t|
t.text :body
t.references :commentable, polymorphic: true # creates commentable_id + commentable_type
end
# Models
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
end
class Post < ApplicationRecord
has_many :comments, as: :commentable
end
class Video < ApplicationRecord
has_many :comments, as: :commentable
end
# Query
post.comments # Comments with commentable_type="Post", commentable_id=post.id
video.comments # Comments with commentable_type="Video", commentable_id=video.idThe commentable_type column stores the class name; commentable_id stores the id.
Rails handles filtering automatically.