rails获取多态类的所有关联类

时间:2013-01-16 01:14:32

标签: ruby-on-rails polymorphic-associations

我有像这样的多态关联(改编自guides.rubyonrails.com):

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

  has_many :employees
end

有没有办法让所有可能的:imageable_types 仅给出图片模型

例如,要在Product模型中获取has_many:quotes类,您可以这样做:

Product.reflect_on_association(:employees).klass 

得到:#=&gt;雇员

现在我想做类似的事情:

Picture.reflect_on_association(:imageable).klass 

这显然会引发异常,但我希望得到类似的结果:#=&gt; [员工,产品]

有办法做到这一点吗? (不试用所有模型来查看它们是否包含has_many:图片)

1 个答案:

答案 0 :(得分:4)

如果不查看所有模型,我无法找到方法,所以我只是调整了这个解决方案:https://stackoverflow.com/a/2315469/1440599