0
votes

My app has User. These users belong to one or many groups. Obviously groups can have many users.

How do I do this in Rails? Is this a has many or a has many through association? What is the name of the third model if it's "has many through"? Nothing seems to make sense. Or is it just something like "group-user-link"?

If I have user_id and group_id in the respective tables, what happends when a User has multiple groups?

1

1 Answers

0
votes

Yes there is a way. If you wanted to have many to many relationship you just need a joining table. Say, your user migh belongs to many groups and and groups may belongs to many users.

So you can define a joining table like this:

rails g model user_group user_id:integer:index group_id:integer:index

This will generate a migration file for you and a model user_group.rb

run the migration and put the following things on the other models:

in user_group.rb

class UserGroup < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

In your user model

  class User < ActiveRecord::Base
     has_many :user_groups
     has_many :groups, through: :user_groups
    ....
    end

so in your group model

 class Group < ActiveRecord::Base
     has_many :user_groups
     has_many :users, through: :user_groups
    .....
    end

And this is how you can achieve your desired relationships.