Retrieve the Active Record Association name between two classes\models
I am using Ruby on Rails 3.0.7 and I would like to know how to retrieve the Active Record Association name between two classes\models.
That 开发者_如何学JAVAis, I have two models
class User < ActiveRecord::Base
has_many :accounts
end
class Account < ActiveRecord::Base
belongs_to :users
end
and I would like to retrieve (on runtime) them association name, in this case accounts
and users
strings.
Is it possible? If so, how can I do that?
UPDATE
If I have more association statements in User
and Account
classes (see the below example), how can I retrieve exactly the User
Account
association name?
class User < ActiveRecord::Base
has_many :accounts
has_many :articles
has_many :comments
end
class Account < ActiveRecord::Base
belongs_to :users
has_many :articles
belongs_to :authorization
end
?
User.reflect_on_all_associations.each do |assoc|
puts "#{assoc.macro} #{assoc.name}"
end
#=> "has_many accounts"
UPD
User.reflect_on_all_associations.select{|a| a.class_name == "Account"}.each do |assoc|
puts "#{assoc.macro} #{assoc.name}"
end
#=> "has_many accounts"
精彩评论