intro
- a model can belong to more than one other models.
- polymorphic
belongs_to
set up an interface that any other models can use.- e.g.
Picture
model belongs toimageable
,Product
model asimageable
. - e.g.
Reputation
model belongs toreputable
,User
model asreputable
.
- e.g.
basic example
- rails generator
rails g picture imageable:references{polymorphic}
-
t.references :imageable, polymorphic: true
- add columns:
:imageable_id
and:imageable_type
- add index:
t.index ["imageable_type", "imageable_id"]
- add columns:
- models:
belongs_to :imageable, polymorphic: true # Picture
has_many :pictures, as: :imageable # User
has_many :pictures, as: :imageable # Product
- rails console:
@user.pictures
@product.pictures
@picture.imageable