ruby-on-railsrails-activerecord

List all associations of a model


I'm looking for a way to list all associations of a model. This is to run some consistency background validation of the big and old database. Too many models to manually discover them and error prone.

I know about Model.new.attributes method. But I don't see which attribute is an association, which model it is, whether it is polymorphic.

Maybe I can assume that something_id is an association and look for something_type attribute to know whether it is polymorphic. But then I can't catch one-to-many and even harder for many-to-many associations.

Is there a more reliable way to do so?


Solution

  • Use reflect_on_all_associations on the class. This will return an Array of subclasses of ActiveRecord::Reflection::AssociationReflection (unfortunately undocumented) for each association. For example, a belongs_to association will return a ActiveRecord::Reflection::BelongsToReflection.

    #klass will return the associated class, #name will return the association name, and from #association_class you can figure out the type of association.

    For example.

    class Parent < ApplicationRecord
    end
    
    class Child < ApplicationRecord
      belongs_to :parent
    end
    
    # Parent
    p Child.reflect_on_all_associations.map(&:klass)