【发布时间】:2016-10-24 16:30:06
【问题描述】:
以下是没有角色的基本模型:
组模型
class Group < ApplicationRecord
has_many :memberships
has_many :users, through :memberships
end
用户模型
class User < ApplicationRecord
has_many :memberships
has_many :groups, through :memberships
end
会员模式
class Membership < ApplicationRecord
belongs_to :group
belongs_to :user
end
每个组应有 1 个(且只有一个)owner、多个admins(由所有者分配),其余为general 成员。此外,所有权角色需要可转让。在我看来,我的选择:
在成员表上创建单个属性
role,并为其分配一个字符串值“所有者”、“经理”或“一般”。 [不好]在成员资格表上为“所有者”、“经理”和“一般”创建多个布尔值。 [不好]
-
创建一个包含 1 列(“名称”)和 3 行(“所有者”、“经理”、“一般”)的
Role模型/表,然后像这样更新我的模型:
榜样
class Role < ApplicationRecord
has_many :memberships
has_many :users, through :memberships
has_many :groups, through :memberships
end
组模型
class Group < ApplicationRecord
has_many :memberships
has_many :users, through :memberships
has_many :roles, through :memberships
end
用户模型
class User < ApplicationRecord
has_many :memberships
has_many :groups, through :memberships
has_many :roles, through :memberships
end
会员模式
class Membership < ApplicationRecord
belongs_to :group
belongs_to :user
belongs_to :role
end
- 直接在组模型上为各种角色创建单独的数组。这看起来真的很愚蠢,因为更新角色需要推送和拼接多个数组,而我必须连接多个数组以呈现一个简单的成员列表。
组模型
class Group < ApplicationRecord
has_many :general_memberships, class_name: 'Membership'
has_many :admin_memberships, class_name: 'Membership'
has_one :owner_membership, class_name: 'Membership'
has_many :users, through :memberships
end
用户模型
class User < ApplicationRecord
has_many :general_memberships, class_name: 'Membership'
has_many :admin_memberships, class_name: 'Membership'
has_many :owner_memberships, class_name: 'Membership'
has_many :groups, through :memberships
end
会员模式
class Membership < ApplicationRecord
belongs_to :group
belongs_to :user
end
我知道有像 CanCanCan(Rails 5 兼容?)和 Groupify 这样的宝石,但我想先了解我的所有选择。我认为选项#3 可能是我最好的,至少在不使用宝石的情况下。想知道社区认为我的方案的最佳做法是什么。
【问题讨论】:
-
找到什么了吗?
-
在下面查看我的答案
标签: ruby-on-rails-5