我有一个非常标准的用户/角色设置回事(用户HABTM角色,角色HABTM用户)。我使用CanCanCan授权,和你有角色定义,你可以在应用程序中做什么。这部分是所有工作正常,但现在我希望能够让用户继承的角色为具有订阅不同成员的一部分。
以下是相关的机型:
class User < ApplicationRecord
has_and_belongs_to_many :roles
has_one :membership_subscription
has_one :membership, through: :membership_subscription
end
class Role < ApplicationRecord
has_and_belongs_to_many :users
end
class MembershipSubscription < ApplicationRecord
belongs_to :user
belongs_to :membership
end
class Membership < ApplicationRecord
has_many :membership_subscriptions
has_many :users, through: :membership_subscriptions
end
我在想,我也许可以只需添加一个has_many: roles
协会成员资格,然后说,通过他们订阅的会员用户has_many
角色,以及当前HABTM关联,使角色直接分配。
这样,您就可以直接连接角色的用户喜欢你现在可以(如一些角色添加剂,并没有涉及到的会员费/类型的话),而且用户将自动继承角色(而再次失去他们)作为其成员的潜艇来去。
那有意义吗?我猜的另一种选择是使用回调模型来处理创建/删除角色关联,但它似乎并不优雅。
任何意见非常感谢!
好了,所以我认为这是一个有效的答案:
首先,更新的车型,以便有是成员身份和角色之间的关联:
class Role < ApplicationRecord
has_and_belongs_to_many :users
has_and_belongs_to_many :memberships
end
class Membership < ApplicationRecord
has_many :membership_subscriptions
has_many :users, through: :membership_subscriptions
has_and_belongs_to_many :roles
end
接下来,创建在可用于检索二者直接分配角色和角色继承用户模型的方法:
def combined_roles
if self.membership == nil
self.roles
else
self.roles + self.membership.roles
end
end
那么无论你需要检查的作用,调用该方法,而不是通常user.roles
的
不知道这是做事情的一个简单的方式,但似乎工作没关系。评论仍然欢迎,如果有更好的方法
编辑:
这允许用户在同一个角色多次有 - 它可以直接分配或继承。修改combined_roles方法,像这样使得它剔除了重复的:
def combined_roles
if self.membership == nil
self.roles
else
(self.roles + self.membership.roles).uniq
end
end