41

Is there a way to find out what associations a model has? Take these 2 models:

class Comment < ActiveRecord::Base
  belongs_to :commentable
end

class Post < ActiveRecord::Base
  has_many :comments
  belongs_to :user
end

I'm looking for something like:

Post.has_many #=> ['comments', ...]
Post.belongs_to # => ['user']
Comment.belongs_to # => ['commentable']

2 Answers 2

89

You're looking for reflect_on_all_associations.

So in short:

Post.reflect_on_all_associations(:has_many)

...will give an array (of object with attributes like name, etc) of all has_many associations.

Sign up to request clarification or add additional context in comments.

Comments

1

The following will list all the associations for a particular instance of Post.

#app/models/post.rb
  def list_associations
    associations = []
    User.reflect_on_all_associations.map(&:name).each do |assoc|
      association = send assoc
      associations << association if association.present?
    end
    associations
  end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.