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.