问题描述
使用Ruby on Rails,我怎么能实现多态的has_many
关系,其中的主人始终是一个已知的,但在协会的项目会出现一些多态的(但同质的)类型,由车主一栏规定?例如,假设在监制
类的has_many
产品,但生产情况实际上可能有许多自行车,或冰棍,或鞋带。我可以很容易地让每个产品类别(自行车,冰棒等)有一个监制一个 belongs_to的
关系,但由于制片比如我怎样才能得到,如果他们的产品集合有不同的类型(每生产实例)的?
Using Ruby on Rails, how can I achieve a polymorphic has_many
relationship where the owner is always of a known but the items in the association will be of some polymorphic (but homogenous) type, specified by a column in the owner? For example, suppose the Producer
class has_many
products but producer instances might actually have many Bicycles, or Popsicles, or Shoelaces. I can easily have each product class (Bicycle, Popsicle, etc.) have a belongs_to
relationship to a Producer but given a producer instance how can I get the collection of products if they are of varying types (per producer instance)?
Rails的多态关联允许生产者属于许多产品,但我需要的关系是周围的其他方式。例如:
Rails polymorphic associations allow producers to belong to many products, but I need the relationship to be the other way around. For example:
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让我像做一个类型列:
So my Producer table already has a "type" column which corresponds to some product class (e.g. Bicycle, Popsicle, etc.) but how can I get Rails to let me do something like:
>> bike_producer.products
#=> [Bicycle@123, Bicycle@456, ...]
>> popsicle_producer.products
#=> [Popsicle@321, Popsicle@654, ...]
如果这是显而易见的,或一个共同的重复对不起;我有令人惊讶的困难很容易实现的。
Sorry if this is obvious or a common repeat; I'm having surprising difficulty achieving it easily.
推荐答案
下面是我目前使用的解决方法。它不提供任何你从真正的ActiveRecord ::协会得到方便的方法(收集操作),但它确实提供了一种方式来获得产品列表给定生成:
Here is the workaround I'm currently using. It doesn't provide any of the convenience methods (collection operations) that you get from real ActiveRecord::Associations, but it does provide a way to get the list of products for a given producer:
class Bicycle < ActiveRecord::Base
belongs_to :producer
end
class Popsicle < ActiveRecord::Base
belongs_to :producer
end
class Producer < ActiveRecord::Base
PRODUCT_TYPE_MAPPING = {
'bicycle' => Bicycle,
'popsicle' => Popsicle
}.freeze
def products
klass = PRODUCT_TYPE_MAPPING[self.type]
klass ? klass.find_all_by_producer_id(self.id) : []
end
end
另一个缺点是,我必须保持字符串类型的映射键入类,但是,可以实现自动化。然而,这种解决方案就足够了,我的目的
Another downside is that I must maintain the mapping of type strings to type classes but that could be automated. However, this solution will suffice for my purposes.
这篇关于Rails的多态的has_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!