Ruby on rails : 创建包含多个用户和一个所有者的组

Ruby on rails : Create group with many user and one owner

我尝试创建一个这样的群组系统: - Groupe可以有很多用户 - 所有用户都可以创建群组 - 但群只有一个主人可以邀请群里的其他用户。

目前我只是有这样的逻辑:

class Groupe
  include Mongoid::Document
  include Mongoid::Timestamps

  has_many :memberships
  has_many :users
end

class Membership
  include Mongoid::Document
  include Mongoid::Timestamps

  belongs_to :user
  belongs_to :project
end

class User
  include Mongoid::Document
  include Mongoid::Timestamps

  has_many :memberships
  has_many :projects
end

当我查看我的数据库 (mongo) 时,我没有看到创建群组的 user_id,我想要,并且我希望创建群组的这个用户成为所有者并可以邀请其他用户。

有人知道如何实现吗?

既然每个组都有一个所有者,那么你可以像这样在组和用户之间定义一个新的关系,

class Group
  include Mongoid::Document
  include Mongoid::Timestamps

  has_many :users
  has_one :owner, class_name: 'User'
end

class User
  include Mongoid::Document
  include Mongoid::Timestamps

  belongs_to :group    
end

创建新组时,尚未设置其所有者。

 g = Group.create
=> #<Group _id: 58fd7f26476bf77e8f52c349, >
 g.owner
=> nil

然后将所有者设置为用户,在您的情况下可能是当前用户。我只是为这个演示创建了一个。这种转让的好处是,以后可以将组所有权转让给另一个人。

 owner = g.users.create
=> #<User _id: 58fd7f47476bf77e8f52c34a, group_id: BSON::ObjectId('58fd7f26476bf77e8f52c349')>
 g.owner = owner
=> #<User _id: 58fd7f47476bf77e8f52c34a, group_id: BSON::ObjectId('58fd7f26476bf77e8f52c349')>

向该组添加更多用户

 g.users.create
=> #<User _id: 58fd7fd4476bf77e8f52c34b, group_id: BSON::ObjectId('58fd7f26476bf77e8f52c349')>
 g.users
=> [#<User _id: 58fd7f47476bf77e8f52c34a, group_id: BSON::ObjectId('58fd7f26476bf77e8f52c349')>, #<User _id: 58fd7fd4476bf77e8f52c34b, group_id: BSON::ObjectId('58fd7f26476bf77e8f52c349')>]

现在群里有两个用户。