为什么用户可以创建帖子,如果`不能:管理,发布`在能力类(CanCanCan)?

时间:2016-06-27 02:22:26

标签: ruby-on-rails authorization cancancan

我是第一次实施CanCanCan。

但令我感到困惑的是,当我在class Foo { public String Name; public Integer Id; } public Foo getObjId(int id) { for (Foo foo : list) { if (foo.getId() == id) { return foo; // foo bar! } } return null; // foo bar not found. } 课程中设置cannot :manage, Post时,用户仍然可以创建帖子。

Ability

我的理解是class Ability include CanCan::Ability def initialize(user) user ||= User.new # if a non-signedin visitor cannot :manage, Post end end 适用于所有操作,因此用户不应对:manage资源执行任何操作。

有人可以提供建议吗?

2 个答案:

答案 0 :(得分:1)

您是否在索引周围添加了这个内容,在您的应用中显示和编辑CRUD链接?这将删除链接所有在一起..我仍然新与cancancan但即使使用load_and_authorize_resources我仍然必须添加if if?在我的链接周围,这解决了我的问题。

<% if can? :manage, Post %> 
  <% link_to "something" some_path %> 
<% end %>

希望这会有所帮助

答案 1 :(得分:1)

首先,您需要在Ability类中定义每种用户类型的功能:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # if a non-signedin visitor

   # abilities of user of type PUBLISHER
   if user.role == "publisher"
     can :create, Post
     can :read, Post
     can :update, Post, user_id: user.id # users can only update their own posts

   # abilities of user of type ADMIN 
   elsif user.role == "admin"
    can :manage, :all # admin can do everything

   # abilities of non-users (e.g. they only can read posts)
   else
     cannot :manage, Post
     can :read, Post
  end
end
  

定义能力并不意味着它们是自动的   适用于控制器。

第二,您需要在每个要向其中应用定义的功能的控制器(例如“后”控制器)中包括load_and_authorize_resource

相关问题