Reputation: 145
I have these two models: Team and User.
Each user can have team and each team has many users. But I want to call team.users with team.members. I managed to do this with class_name, but I also need to have access to Team by User. In other words user.team should return me the team, in which the User is. Here is what I came up with...
My models are as follows:
class Team < ActiveRecord::Base
has_many :members, foreign_key: 'id', class_name: 'User', :inverse_of => :team
end
class User < ActiveRecord::Base
belongs_to :team, :inverse_of => :user
end
(I tried with :inverse_of => :members too, inside the User model.)
Upvotes: 1
Views: 1665
Reputation: 6711
You got the :inverse_of
right, at least when you use :inverse_of => :members
. The problem here is the foreign key. foreign_key
specifies the name of the key-column in the other table, so in your case in the user-table. If you specify just id
, the id of the user would be used. Just leave it to the default by not specifying an foreign key, then its team_id
.
class Team < ActiveRecord::Base
has_many :members, :class_name => 'User', :inverse_of => :team
end
class User < ActiveRecord::Base
belongs_to :team, :inverse_of => :members
end
And try to not mix hash-syntax from ruby 1.8 (:key => 'value'
) with the new syntax from ruby 1.9 (key: 'value'
).
Upvotes: 1