Ruby on rails 获取多态关联的有效模型列表
以多态关联为例,使用以下模型:Ruby on rails 获取多态关联的有效模型列表,ruby-on-rails,ruby-on-rails-4,associations,polymorphic-associations,Ruby On Rails,Ruby On Rails 4,Associations,Polymorphic Associations,以多态关联为例,使用以下模型: 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: :im
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\u类型
s
例如,这样它就会返回:
[:employee,:product]
我的问题是,你为什么需要这个?我不完全确定,但我认为您可能正在寻找:
Picture.select(:imageable_type).distinct.pluck(:imageable_type)
这是6年前的答案。什么是它在项目中的每个模型上循环并使用方法反射所有关联寻找的关联都有多个或只有一个关联。你的问题是一个好问题。。。也许我把我的模型设置错了。。。关于您的解决方案,它对我不起作用,因为这只会返回正在使用的
:imageable_type
s。。。我正在寻找所有类型,无论是在使用中,还是可以使用。好吧,就像我说的,也许我的模型设置错了。实际上,我拥有的是一个多态的基础报告
,然后是具体的报告(例如ReportA
,ReportB
,ReportC
,等等)。我想要的是Report*
列表,该列表已定义,以便我可以创建一个下拉列表来选择适当的具体报告。