Search code examples
ruby-on-railspolymorphic-associationshelper

Finding all by Polymorphic Type in Rails?


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

...or

BuiltInRailsPolymorphicHelper.all("assignable")

That would be nice.

Edit:

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


Solution

  • 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']