【问题标题】:Getting a list of valid models for a polymorphic association获取多态关联的有效模型列表
【发布时间】:2016-10-24 22:48:06
【问题描述】:

rubyonrails.org 中的多态关联示例并使用以下模型:

class Picture < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end

class Employee < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

class Product < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

如何找到有效的imageable_types?

例如以便它返回:[:employee, :product]

【问题讨论】:

  • 6年前就有这个答案stackoverflow.com/questions/2315239/…。它是什么循环遍历项目中的每个模型并使用方法 reflect_on_all_associations 查找 has_many 或 has_one 关联。

标签: ruby-on-rails ruby-on-rails-4 associations polymorphic-associations


【解决方案1】:

我的问题是你为什么需要这个?我不完全确定,但我认为您可能正在寻找:

Picture.select(:imageable_type).distinct.pluck(:imageable_type)

【讨论】:

  • 您的问题是个好问题...也许我的模型设置错误...关于您的解决方案,它对我不起作用,因为那只会返回 :imageable_types正在使用中...我正在寻找 ALL 类型,无论是在使用中,还是 可以 使用。好的,就像我说的,也许我的模型设置错误。实际上,我拥有的是一个多态的基础Report,然后是具体的报告(例如ReportAReportBReportC 等)。我想要的是定义的Report* 列表,以便我可以创建一个下拉列表来选择适当的具体报告。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
相关资源
最近更新 更多