Relationships of model
How can I get all relationships for model. IE, I've got User
model:
class User < AR开发者_StackOverflow中文版::Base
has_many :messages, :foreign_key => 'author'
has_many :posts
belongs_to :role
end
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
Outputs:
has_many messages
has_many posts
belongs_to role
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.
精彩评论