有没有办法列出所有belongs_to 关联? [英] Is there a way to list all belongs_to associations?

查看:52
本文介绍了有没有办法列出所有belongs_to 关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您可以使用类的 reflections 哈希来执行此操作.可能有更直接的方法,但这是有效的:

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) }

这篇关于有没有办法列出所有belongs_to 关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆