Many-to-Many Polymorphic Relationships In Rails

Posted By Weston Ganger

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:

Article Topic:Software Development - Ruby / Rails

Date:October 19, 2015