Rails has_many和has_many通过
问题描述:
我很困惑如何去解决这个问题。我通过会员模式连接用户和组,但我也希望用户能够创建新组。显然,一个组必须属于一个用户,但这些组也属于用户通过成员表。Rails has_many和has_many通过
我在我的user.rb文件中有这个,但我觉得它是错误的。我是否删除第一个,并且只有一个?在这种情况下,我如何在团队的创建者中工作?
class User < ApplicationRecord
has_many :groups
has_many :groups, through: :memberships
end
换句话说,用户是许多组的成员,也是许多组的创建者。成员资格表只有两列(组ID和用户ID)。此列中的用户标识用于存储属于该组成员的用户。我被困在创建组的用户该怎么做。
答
您应该在组和用户之间有两个关系。一个反映了用户创建了一个组,一个用户属于一个组的事实。你可以通过配置你的关系的命名来反映这个想法。你也必须在你的Groups表中添加一个user_id字段。
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
这就是我一直在寻找,谢谢。 – ddonche