/ rails

Polymorphic associations

Consider a scenario where multiple models has 1 to N relationship with one model.

For example.

Consider models like School, College, Event and Semester are having multiple relationship with a single model i.e Student. It will not be a good idea to have multiple foreign keys to student model like school_id, college_id, event_id and semester_id into one table.

So whenever you have a scenario like this, you have to follow polymorphic associations. For example:

In your models i.e school.rb, college.rb, semester.rb and event.rb, define something like this:

class School < ActiveRecord::Base

has_many :students, :class_name => "Student", :as => :rollable, :dependent => :destroy

end

class College < ActiveRecord::Base

has_many :students, :class_name => "Student", :as => :rollable, :dependent => :destroy

end

class Semester < ActiveRecord::Base

has_many :students, :class_name => "Student", :as => :rollable, :dependent => :destroy

end

class Event < ActiveRecord::Base

has_many :students, :class_name => "Student", :as => :rollable, :dependent => :destroy

end

class Student < ActiveRecord::Base

belongs_to :rollable, :polymorphic => true

end

Advantage :

The advantage of using polymorphic association is, you don’t need to create school_id, college_id, semester_id and event_id columns in the students table. So when you create migration, you will have to create just two columns i.e.

t.integer :rollable_id

t.string :rollable_type

So for example, colleges the entry will have rollable_id as specific college id and rollable_type as College.