2011-12-03 27 views

Trả lời

30

Bạn có thể sử dụng hàm băm reflections của lớp để thực hiện việc này. Có thể có những cách đơn giản hơn, nhưng hoạt động này:

# 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) } 
16
Thing.reflections.collect{|a, b| b.class_name if b.macro==:belongs_to}.compact 
#=> ["Foo", "Bar"] 

tất nhiên, bạn có thể vượt qua: has_many, hoặc bất kỳ hiệp hội khác quá

+0

shit doped! tốt đẹp....! –

34

Bạn có thể sử dụng phương pháp reflect_on_all_associations từ Reflection Đối ví dụ:

Thing.reflect_on_all_associations(:belongs_to) 
Các vấn đề liên quan