CanCan - 如何正确设置嵌套资源能力
在我的应用程序中,我有以下模型:
Users
Groups
Permissions (user_id, group_id, role_id)
其中 role_id 1:admin,2:member
我想确保我正确理解 CanCan。在ability.rb 文件中,我只希望组管理员(permission.role_id == 1)能够更新/销毁/创建新的组权限。
Permission.role_id == 2,成员,应该只是能够读取该组以及该组的权限。除非有能力破坏他们的团体许可。
这是我的 CanCanability.rb 文件:
class Ability
include CanCan::Ability
def initialize(current_user, groupid_viewing)
current_user ||= User.new #Guest user (not signed in)
if groupid_viewing && current_user.try(:role, groupid_viewing) == 'Admin'
can :manage, Group
can [:create, :update], Permission do |permission|
current_user.try(:role, groupid_viewing) == 'Admin'
end
class GroupsController < ApplicationController
....
def current_ability
@current_ability ||= Ability.new(current_user, params[:group_id] && params[:group_id].to_i)
end
class ApplicationController < ActionController::Base
def current_ability
@current_ability ||= Ability.new(current_user, nil) #(user, group)
end
In my app I have the following models:
Users
Groups
Permissions (user_id, group_id, role_id)
Where role_id 1: admin, 2: member
I want to make sure I'm understanding CanCan correctly. In the ability.rb file, I only want group admins (permission.role_id == 1) to be able to update/destroy/create new group permissions.
permission.role_id == 2, members, should just be able to read the group and the group's permissions. Except for having the ability to destroy their group permission.
Here is my CanCan ability.rb file:
class Ability
include CanCan::Ability
def initialize(current_user, groupid_viewing)
current_user ||= User.new #Guest user (not signed in)
if groupid_viewing && current_user.try(:role, groupid_viewing) == 'Admin'
can :manage, Group
can [:create, :update], Permission do |permission|
current_user.try(:role, groupid_viewing) == 'Admin'
end
class GroupsController < ApplicationController
....
def current_ability
@current_ability ||= Ability.new(current_user, params[:group_id] && params[:group_id].to_i)
end
class ApplicationController < ActionController::Base
def current_ability
@current_ability ||= Ability.new(current_user, nil) #(user, group)
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您还需要指定
role_id:2
的能力。此外,无需按照您的方式创建
current_ability
。它应该是一个 after_create 回调,在创建成员或管理员时分配能力。
You also need to specify the abilities for the
role_id:2
.Also, there is no need of creating
current_ability
the way you are doing.It should be an after_create callback that should assign abilities when the Member or Admin is created.