I need to list all belongs_to associations in a model object and iterate through them. Is there a way to do this?
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 .
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.
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.
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.
You can make use of reflect_on_all_associations method from Reflection For example:
Thing.reflect_on_all_associations(:belongs_to)
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) }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With