简体   繁体   中英

Rails has_many and has_many through

I am confused on how to go about approaching this. I am connecting users and groups through the membership model, but I also want users to be able to create new groups. Clearly a group must then belong to a user, but the groups also belong to users through the memberships table.

I have this in my user.rb file, but I feel it is wrong. Do I remove the first one and just have the through one? How do I work in the creator of the group in that case?

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

In other words, the user is a member of many groups, but also the creator of many groups. The memberships table only has two columns (group id and user id). The user id in this column is used to store users who are members of that group. I am stuck on what to do about the user who created the group.

You should have two relationships between Groups and Users. One reflecting the fact that a user created a group, and one that a user belongs to a group. You can reflect this idea by configuring the naming of your relationships. You will have to add a user_id field to your Groups table as well.

class User < ApplicationRecord
  has_many :created_groups, class_name: "Group"
  has_many :memberships
  has_many :groups, through: :memberships
end

class Group < ApplicationRecord
  belongs_to :creator, class_name: "User"
  has_many :memberships
  has_many :subscribers, through: :memberships, source: :user
end

class Membership < ApplicationRecord
  belongs_to :user
  belongs_to :group
end

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