ruby-on-rails 有没有办法列出所有的belongs_to关联?

4nkexdtk  于 2023-08-08  发布在  Ruby
关注(0)|答案(4)|浏览(125)

我需要列出模型对象中所有的belongs_to关联并遍历它们。有办法做到这一点吗?

hiz5n14c

hiz5n14c1#

您可以使用Reflection中的reflection_on_all_associations方法例如:

Thing.reflect_on_all_associations(:belongs_to)

字符串

bvn4nwqk

bvn4nwqk2#

您可以使用类的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) }

字符串

mwkjh3gx

mwkjh3gx3#

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

字符串
当然,您也可以传递:has_many或任何其他关联

cyej8jka

cyej8jka4#

最新消息:
在Rails 7上运行,该方法现在是:

Thing._reflections

字符串

相关问题