Ben*_*ang 40
您可以使用Reflection中的reflect_on_all_associations方法例如:
Thing.reflect_on_all_associations(:belongs_to)
Run Code Online (Sandbox Code Playgroud)
num*_*407 34
您可以使用类的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) }
Run Code Online (Sandbox Code Playgroud)
okl*_*liv 19
Thing.reflections.collect{|a, b| b.class_name if b.macro==:belongs_to}.compact
#=> ["Foo", "Bar"]
Run Code Online (Sandbox Code Playgroud)
当然,您也可以传递:has_many或任何其他关联
| 归档时间: |
|
| 查看次数: |
15840 次 |
| 最近记录: |