在Rails中按多态类型查找所有内容? [英] Finding all by Polymorphic Type in Rails?

查看:86
本文介绍了在Rails中按多态类型查找所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有办法在Rails中查找特定多态类型的所有多态模型?因此,如果我有Group,Event和Project,它们都带有如下声明:

Is there a way to find all Polymorphic models of a specific polymorphic type in Rails? So if I have Group, Event, and Project all with a declaration like:

has_many :assignments, :as => :assignable

我可以做类似的事情吗?

Can I do something like:

Assignable.all

...或

BuiltInRailsPolymorphicHelper.all("assignable")

那很好.

...使得Assignable.all返回[Event, Group, Product](类数组)

... such that Assignable.all returns [Event, Group, Product] (array of classes)

推荐答案

没有直接的方法.我为ActiveRecord::Base编写了这个猴子补丁. 这将适用于任何课程.

There is no direct method for this. I wrote this monkey patch for ActiveRecord::Base. This will work for any class.

class ActiveRecord::Base

  def self.all_polymorphic_types(name)
    @poly_hash ||= {}.tap do |hash|
      Dir.glob(File.join(Rails.root, "app", "models", "**", "*.rb")).each do |file|
        klass = File.basename(file, ".rb").camelize.constantize rescue nil
        next unless klass.ancestors.include?(ActiveRecord::Base)

        klass.
          reflect_on_all_associations(:has_many).
          select{ |r| r.options[:as] }.
          each do |reflection|
            (hash[reflection.options[:as]] ||= []) << klass
          end
      end
    end
    @poly_hash[name.to_sym]
  end

end

现在您可以执行以下操作:

Now you can do the following:

Assignable.all_polymorphic_types(:assignable).map(&:to_s)
# returns ['Project', 'Event', 'Group']

这篇关于在Rails中按多态类型查找所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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