Help with hmabt relationships


I want to have this table structure with users and groups
A user can be in more than 1 group and a group has more than 1 user.

class User < ActiveRecord::Base
has_many_and_belongs_to :groups

class Group < ActiveRecord::Base
has_many_and_belongs_to :users

I was wondering if i can do this
for group in user.groups
…do stuff
for user in group.users
…do stuff

I need both loops, can i do that, or do i need another structure…

Thanks in advance

Yes you can do that fine. However, you may be missing a conceptual
model like “memberships”. Not sure if you are using edge_rails but you
could have a user belong to a group through a membership. The groups
may contain users through their memberships. In this way you could
also capture other information (for example, most recent member, most
active member etc.) that might fall through silently in a typical

On 1/23/06, Brutyn N. [email protected] wrote:

has_many_and_belongs_to :users

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs