I have two tables, users and groups. A user can belong to many groups. A group can have many users.
So I have created a have_and_belongs_to_many relationship between users and groups using a join table, groups_users. This all works as expected.
What I would also like to do is specify an ACTIVE group for each user. Were it not for the habtm relationship I have already defined, I would create a column “group_id” in users for the active group, and then I would define a one-to-many relationship between the models as follows:
class User < ActiveRecord::Base
belongs_to :group
end
class Group < ActiveRecord::Base
has_many :users
end
This didn’t work. I could not access group properties like “@user.group.name”. I suspect that I’m asking too much of Rails by specifying two relationships.
So I have three questions.
- I could very easily understand if combining the two relationships confuses Active Record . Is that the case?
- If so, how would you implement these relationships? Right now I’m just manually using the group_id, but that feels messy.
- Regardless of whether I am using Active Record magic or manually setting the active group, it is possible for a user’s active group to be outside the group’s they belong to using the first habtm relationship. Any thoughts on how to implement this with the constraint that the active group must be a group that the user belongs to?
Thanks for any insights. I am a couple of weeks into the Rails learning curve and I think that getting to the bottom of this little problem will deepen my understanding of models and table relationships quite a bit.