[英]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: 我熟悉使用rails的多态关联,其中模型可以被声明为多态,以获得属于众多其他模型的能力,例如:
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: 对于您的宠物示例, STI可能是一个解决方案:
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. 这仍然可以让你访问@person.pets
和@dog.owner
, @pet.owner
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.