Rails

Many-to-Many Polymorphic Relationships In Rails

Posted by Weston Ganger on October 19, 2015

Imagine the following example where:

  • A person has many animals (cats and dogs)
  • A cat has many people(in the family)
  • A dog has many people(in the family)
  • All of this is through the Home

Heres how to accomplish that scenario:


class Home < ActiveRecord::Base
  belongs_to :person
  belongs_to :animal, polymorphic: true
end

class Person < ActiveRecord::Base
  has_many :animals, through: :home
end

class Dog < ActiveRecord::Base
  has_many :people, through: :home, as: :animal
end

class Cat < ActiveRecord::Base
  has_many :people, through: :home, as: :animal
end

Not too complicated but it does require a through model.


Related External Links:


Posted in Rails and Tagged with rails polymorphic relationships active-record 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts