查找所有多态类型在Rails的?
-
22-09-2019 - |
题
有没有办法找到Rails的特定多态型的所有型号多态?所以,如果我有组,事件和项目都带有声明如下:
has_many :assignments, :as => :assignable
我可以这样做:
Assignable.all
...或
BuiltInRailsPolymorphicHelper.all("assignable")
这将是很好。
编辑:
...使得Assignable.all
返回[Event, Group, Product]
(类的数组)
解决方案
有这个没有直接的方法。我写了ActiveRecord::Base
这只猴子补丁。
这将用于任何类工作。
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
现在,你可以做到以下几点:
Assignable.all_polymorphic_types(:assignable).map(&:to_s)
# returns ['Project', 'Event', 'Group']
其他提示
我创建了一个多态模型类与方法“全部”来测试此。
class Profile
# Return all profile instances
# For class return use 'ret << i' instead of 'ret << i.all'
def self.all
ret = []
subclasses_of(ActiveRecord::Base).each do |i|
unless i.reflect_on_all_associations.select{|j| j.options[:as] == :profile}.empty?
ret << i
end
end
ret.flatten
end
def self.all_associated
User.all.map{|u| u.profile }.flatten
end
end
下面是我的应用程序设置:
User < ActiveRecord::Base
belongs_to :profile, :polymorphic => true
end
Student < ActiveRecord::Base
has_one :user, :as => :profile
end
您应该能够只使用相关的集合:
model.assignments.all
不隶属于 StackOverflow