Is there a way to list all belongs_to associations?

后端 未结 3 446
悲哀的现实
悲哀的现实 2020-12-13 06:21

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

相关标签:
3条回答
  • 2020-12-13 06:44
    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

    0 讨论(0)
  • 2020-12-13 06:46

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

    Thing.reflect_on_all_associations(:belongs_to)
    
    0 讨论(0)
  • 2020-12-13 06:56

    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) }
    
    0 讨论(0)
提交回复
热议问题