通过Rails中的Polymorphic Type查找所有内容?
有没有办法在Rails中找到特定多态类型的所有多态模型? 因此,如果我有Group,Event和Project都具有以下声明:
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 if klass.nil? or !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']
我使用方法’all’创建了一个多态模型类来测试它。
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