我有一个 Rails 应用程序,使用 CanCan 进行授权。我有可以在组中拥有成员资格的用户。我想创建一个 CanCan 规则,该规则仅在用户还不是该组的成员时才授权用户创建组成员资格。到目前为止,我一直无法弄清楚魔术:
class Group < ActiveRecord::Base
has_many :memberships
has_many :members, :through => :memberships
end
class Membership < ActiveRecord::Base
belongs_to :member, class_name: 'User'
belongs_to :group
end
class User < ActiveRecord::Base
has_many :groups, through: :memberships
has_many :memberships, foreign_key: 'member_id'
end
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
# One of my sad attempts...
can :create, Membership do |membership|
!membership.group.has_member(user)
end
end
end
<% if can? :create, Membership %>
View code for creating memberships...
<% end %>
感谢您的协助。另外,我知道 CanCanCan 是 CanCan 的继承者。CanCanCan 的回答会很好。