Rails 多态 has_many [英] Rails Polymorphic has_many

查看:32
本文介绍了Rails 多态 has_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Ruby on Rails,我如何实现多态 has_many 关系,其中所有者始终是已知的,但关联中的项目将是某种多态(但同质)类型,由指定在所有者列?例如,假设 Producerhas_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

所以我的 Producer 表已经有一个type"列,它对应于某个产品类别(例如自行车、冰棒等),但是我怎样才能让 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::Associations 中获得的任何便捷方法(收集操作),但它确实提供了一种获取给定生产者的产品列表的方法:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆