Trenton Tyler
Trenton Tyler

Reputation: 1712

Rails creating user groups

I am a bit new to rails and I want to create user groups in my application. A user can belong to many groups and a group can have many users in it. For instance there would be a first grade group with all first grade teachers in it and they will also belong to a number of other groups.

This is my current code.

class Group < ApplicationRecord
  has_many :users
end

class User < ApplicationRecord
  belongs_to :group
end

At the moment if I assign a user to a group in the Ruby console it only allows one group id. How can I make a user have multiple group_ids?

Upvotes: 4

Views: 1909

Answers (1)

Ronan Lopes
Ronan Lopes

Reputation: 3398

In that case, you should have a NxN (many to many) relationship. So you'll need an additional model for that. You can generate it like this:

rails g model UserGroup user:references group:references

Then, you change your models like this:

class Group < ApplicationRecord
  has_many :user_groups
  has_many :users, through: :user_groups
end

class User < ApplicationRecord
  has_many :user_groups
  has_many :groups, through: :user_groups
end

That way, you can access a User groups like this:

User.first.groups

or a Group users like this:

Group.first.users

Hope this helps... good luck!

Upvotes: 6

Related Questions