模型关系 [英] Relationships of model
本文介绍了模型关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取模型的所有关系.IE,我有 User
模型:
How can I get all relationships for model. IE, I've got User
model:
class User < AR::Base
has_many :messages, :foreign_key => 'author'
has_many :posts
belongs_to :role
end
那么我怎么知道User
模型有哪些关系呢?和foreign_keys,如果它们被呈现.
So how can I know which relationships User
model has got? And foreign_keys if they are presented.
推荐答案
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<的数组/a> 对象.它们也支持其他方法,用于查询每个关联的选项哈希和其他有用的东西.
The reflect_on_all_associations
method return an array of MacroReflection objects. They support other methods as well, for querying the options hash of each association and other useful stuff.
这篇关于模型关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文