Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to list all belongs_to associations?

I need to list all belongs_to associations in a model object and iterate through them. Is there a way to do this?

like image 848
AnarchoTroll Avatar asked Dec 03 '11 22:12

AnarchoTroll


People also ask

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 .

What is a polymorphic association in Rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.

What is association in ruby on 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.

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


3 Answers

You can make use of reflect_on_all_associations method from Reflection For example:

Thing.reflect_on_all_associations(:belongs_to) 
like image 87
Ben Zhang Avatar answered Sep 29 '22 23:09

Ben Zhang


You could make use of the class's reflections hash to do this. There may be more straightforward ways, but this works:

# say you have a class Thing class Thing < ActiveRecord::Base   belongs_to :foo   belongs_to :bar end  # this would return a hash of all `belongs_to` reflections, in this case: # { :foo => (the Foo Reflection), :bar => (the Bar Reflection) } reflections = Thing.reflections.select do |association_name, reflection|    reflection.macro == :belongs_to end  # And you could iterate over it, using the data in the reflection object,  # or just the key. # # These should be equivalent: thing = Thing.first reflections.keys.map {|association_name| thing.send(association_name) } reflections.values.map {|reflection| thing.send(reflection.name) } 
like image 37
numbers1311407 Avatar answered Sep 30 '22 00:09

numbers1311407


Thing.reflections.collect{|a, b| b.class_name if b.macro==:belongs_to}.compact 
#=> ["Foo", "Bar"]

of course, you can pass :has_many, or any other associations too

like image 40
okliv Avatar answered Sep 30 '22 00:09

okliv