我一直在使用cancan gem进行railscast,但我仍坚持如何只允许用户访问他们自己的显示页面.
我的代码看起来像这样:
能力模型
class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.role == "admin" can :manage,:all else can :read,:all if user.role == "author" can :create,Review can :update,Review do |review| review.try(:user) == user end can :update,User do |user| user.try(:current_user) == current_user end end if user.role == "owner" can :update,Venue end end end end
用户控制器
class UsersController < ApplicationController load_and_authorize_resource end
用户(作者)只能更新自己的评论,但目前可以通过更改URL查看所有用户显示的页面.
我在这里错过了什么?
解决方法
约束可以在你的能力等级中传递,甚至比你尝试的方式更容易.我确信这会缺少你想要的一些能力,但这应该让你开始.我假设评论:belongs_to具有外键的用户:user_id.它看起来你需要一些类似的场地约束,但是你的代码中没有它,所以我没有把它放在这里.
class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.role == "admin" can :manage,:all elsif user.role == "author" can :create,Review can :update,Review,:user_id => user.id can [:show,:update],User,:id => user.id elsif user.role == "owner" can :update,Venue can [:show,:id => user.id else can [:show,:id => user.id end end end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。