Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails method to get the association name of a model

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'] 
like image 625
DiegoSalazar Avatar asked Jan 07 '10 22:01

DiegoSalazar


People also ask

What are associations in Rails?

Association in Rails defines the relationship between models. It is also the connection between two Active Record models. To figure out the relationship between models, we have to determine the types of relationship. Whether it; belongs_to, has_many, has_one, has_one:through, has_and_belongs_to_many.

What is difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user .


2 Answers

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.

like image 174
rfunduk Avatar answered Nov 04 '22 16:11

rfunduk


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 
like image 31
Obromios Avatar answered Nov 04 '22 18:11

Obromios