How do I create a functioning has_and_belongs_to_many relationship.

I am trying to create a group in which people can create but also be a part of. They can create many groups and also belong to many of these groups.

Posted over 4 years ago by dylan
Posted over 4 years ago by Alex Yang

If you don't need to track the group owner, then a has_and_belongs_to_many association is perfect for setting this up. Here's how it would look:

class User < ActiveRecord::Base
has_and_belongs_to_many :groups
end

class Group < ActiveRecord::Base
has_and_belongs_to_many :users
end

Here are a couple more links you may find helpful:

More detail about this specific setup:
http://stackoverflow.com/questions/15442450/many-to-many-users-and-groups-but-groups-have-owners

More info about Rails associations in general:
http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

Hope that helps!

2
Posted over 4 years ago by dylan

That helps a lot! thank you.
Just one more thing, how would I set it up if I want to assign the person that created the group as "Group Creator?" what kind of relationship would I use?

1
Posted over 4 years ago by Alex Yang

You're starting to get into the advanced stuff, but here's how I'd do it:

class User < ActiveRecord::Base
has_many :owned_groups, class_name: "Group", foreign_key: "owner_id"
has_and_belongs_to_many :groups
end

class Group < ActiveRecord::Base
belongs_to :owner, class_name: "User"
has_and_belongs_to_many :users
end

If you use this, it's important that you take the time to understand it, because you'll need to set up the right lookup columns in your databases as well.

2
Posted over 4 years ago by dylan

PERFECT! thanks Alex

1