2010-07-05 80 views
2

如何获取模型的所有关系。 IE浏览器,我有User型号:模型的关系

class User < AR::Base 
    has_many :messages, :foreign_key => 'author' 
    has_many :posts 
    belongs_to :role 
end 

那么,怎样才能知道User模式已经得到了其中的关系?如果他们被介绍,则使用foreign_keys。

回答

7
User.reflect_on_all_associations.each do |assoc| 
    puts "#{assoc.macro} #{assoc.name}" 
end 

输出:

has_many messages 
has_many posts 
belongs_to role 

reflect_on_all_associations方法返回MacroReflection对象的数组。它们也支持其他方法,用于查询每个关联和其他有用内容的选项散列。