简体   繁体   中英

Rails inverse polymorphic association

I'm familiar with using rails' polymorphic associations, where a model can be declared polymorphic to gain the capability of belonging to a multitude of other models, such as:

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

class Article < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Photo < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Event < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

Is there a common pattern to deal with the inverse case, where a model can have a multitude of other models that will be accessed through the same interface (eg a person has many pets, where pets can be either dogs, cats, etc.)? Should I just create a virtual attribute?

For your pets example, STI may be a solution:

class Person < ActiveRecord::Base
  has_many :pets
end

class Pet < ActiveRecord::Base
  belongs_to :owner, class_name: "Person", foreign_key: "person_id"
  # Be sure to include a :type attribute for STI to work
end

class Dog < Pet
end

class Cat < Pet
end

This should still give you access to @person.pets and @dog.owner , @pet.owner , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM