views:

93

answers:

1

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.

  1. I could very easily understand if combining the two relationships confuses Active Record . Is that the case?
  2. If so, how would you implement these relationships? Right now I’m just manually using the group_id, but that feels messy.
  3. 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.

+1  A: 

Greg - I've done this before, similar to what as your proposing. I used a "primary_group" instead of "group" and set the foreign_key to be "primary_group_id" and the :class_name => 'Group'

I don't use has_and_belongs_to_many very often so I don't know if that would be causing an issue, but I don't think so - at least not with the user model. You don't have a #group method, so setting belongs_to should be OK. I don't know if you absolutely must have have a has_many :users method on the group, but you may not need it anyway. This will certainly cause a collision with the 'users' method that habtm creates. If you do need this, try has_many :primary_users and set the :foreign_key => :primary_group_id

Just some thoughts. You should be able to do what you're doing now, so not sure what's failing.

Swards
Thanks Swards. Things are working now, so I think I had another bug somewhere. I have taken your approach of renaming the association (primary_group) to make things more clear.
Greg