Мне нужно перечислить все ассоциации belongs_to в объекте модели и выполнить итерацию через них. Есть ли способ сделать это?
Есть ли способ перечислить все ассоциации belongs_to?
Ответ 1
Вы можете использовать хэш класса reflections
для этого. Там могут быть более простые способы, но это работает:
# 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) }
Ответ 2
Вы можете использовать метод reflection_on_all_associations из Reflection Например:
Thing.reflect_on_all_associations(:belongs_to)
Ответ 3
Thing.reflections.collect{|a, b| b.class_name if b.macro==:belongs_to}.compact
#=> ["Foo", "Bar"]
конечно, вы можете передать: has_many или любые другие ассоциации тоже