Alex Rivera | Logout

rails method to get the association name of a model

Asked 2010-01-07T22:36:25.163
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']
Edit
Report

1 Answer

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.

answered 2010-01-07T22:50:15.343

Your Answer