模型的关系

如何获得模型的所有关系。 IE,我有User模型:

 class User  'author' has_many :posts belongs_to :role end 

那么我怎么知道User模型有哪些关系呢? 和foreign_keys如果被呈现。

 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对象。 它们也支持其他方法,用于查询每个关联的选项哈希和其他有用的东西。