使用
Ruby on Rails,如何实现一个多态的has_many关系,其中所有者始终是已知的,但关联中的项将是一些多态(但同质的)类型,由所有者的列指定?例如,假设Producer类has_many产品,但生产者实例可能实际上有许多自行车,或者Popsicles或Shoelaces.我可以轻松地让每个产品类(自行车,冰棒等)与生产者具有belongs_to关系,但是给出生产者实例如果产品的类型不同(每个生产者实例),我如何获取产品的集合?
Rails多态协会允许生产者属于许多产品,但我需要的关系是相反的.例如:
class Bicycle < ActiveRecord::Base belongs_to :producer end class Popsicle < ActiveRecord::Base belongs_to :producer end class Producer < ActiveRecord::Base has_many :products,:polymorphic_column => :type # last part is made-up... end
所以我的生产者表已经有一个“类型”列对应于某些产品类(例如自行车,冰棒等),但是如何让Rails让我做一些类似的事情:
>> bike_producer.products #=> [Bicycle@123,Bicycle@456,...] >> popsicle_producer.products #=> [Popsicle@321,Popsicle@654,...]
对不起,如果这是明显的或常见的重复;我很难实现这个难题.
解决方法
您必须在生产者上使用STI,而不是使用产品.通过这种方式,对于每种类型的生产者,都有不同的行为,但是在单个生产者表中.
(几乎)没有多态性!
class Product < ActiveRecord::Base # does not have a 'type' column,so there is no STI here,# it is like an abstract superclass. belongs_to :producer end class Bicycle < Product end class Popsicle < Product end class Producer < ActiveRecord::Base # it has a 'type' column so we have STI here!! end class BicycleProducer < Producer has_many :products,:class_name => "Bicycle",:inverse_of => :producer end class PopsicleProducer < Producer has_many :products,:class_name => "Popsicle",:inverse_of => :producer end