简体   繁体   中英

Ruby on Rails - Users in Groups

I'm trying to implement a Group system where a User can create a Group and other Users can join the Group.

class User < ApplicationRecord
    has_many :groups
end

class Group < ApplicationRecord
    belongs_to :owner, :class_name => "User"
    has_many :members, :class_name => "User"
end

When checking the owner, I can successfully use:

<% if current_user == @group.owner %>

But I'm unable to check the members of the group with:

<%= @group.members.count %>

As I run into an error:

SQLite3::SQLException: no such column: users.group_id: SELECT COUNT(*) FROM "users" WHERE "users"."group_id" = ?

I think it has something to do with how my Users are setup, but can't figure it out.

Also, once I'm able to have a list containing all the Users that have 'joined' the Group, how do I add/remove Users from that?

Thanks.

There are two possibilities here:

One User can belong to Many Groups

If one user will belong to only one group which your association says then you need to add group_id attribute to the User model or users table which will identify in which group the user belongs to. Currently you don't have that column that is why it is throwing an exception. Regarding the owner you have a owner_id in you Group table which gives you the owner which is an User object.

User - group_id
Group - owner_id

But this way you will have only one group associated with the User , so your has_many :groups is of no use in User model. To have multiple you need another table in between:

One User will belong to only One Group

If one user can belong to multiple groups then you need to create one more model like UserGroups which will have user_id and group_id and the associations will go like this:

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

class Group < ActiveRecord::Base
  has_many :user_groups
  has_many :users, through: :user_groups #This can be members also using `class_name`
end

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

A User also belongs to a group (you forgot that). In your group schema you need a group id so that once a group is created other users can join that specific group. Both owner and member should be of type "references" in your schema. With that you should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM