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