activerecord - Polymorphic Associations - rails -


i have trouble understanding polymorphic associations in rails. how

class picture < applicationrecord   belongs_to :imageable, polymorphic: true end  class employee < applicationrecord   has_many :pictures, as: :imageable end  class product < applicationrecord   has_many :pictures, as: :imageable end 

different from

class picture < applicationrecord   belongs_to :employee   belongs_to :product end  class employee < applicationrecord   has_many :pictures end  class product < applicationrecord   has_many :pictures end 

in second case need add 2 foreign keys i.e employee_id , product_id in pictures table.

where in first case t.references :imageable, polymorphic: true in pictures migration add 2 fields in pictures table i.e

t.integer :imageable_id t.string  :imageable_type 

imagable_type field name of class whom associating model , imagable_id hold id of record.

e.g,

typical rows of picture table like

id | name | imagable_id | imagable_type |  1  | pic1 | 1           | employee      | 2  | pic2 | 3           | product       | 

so here, picture of first row belong employee model holding picture of employee id 1. second row belong product model holding picture of product id 3

advantages of first approach can associate picture model other model in future without having add foreign key it.

just add line

has_many :pictures, as: :imageable 

and association set.


Comments