Is there a way to list all belongs_to associations?

后端 未结 3 450
悲哀的现实
悲哀的现实 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: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) }
    

提交回复
热议问题