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

问题描述 投票:1回答:2

我是第一次实施CanCanCan。

但我很困惑为什么当我在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适用于所有操作,因此用户不应该对post资源做任何事情。

任何人都可以建议吗?

ruby-on-rails authorization cancancan
2个回答
1
投票

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

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

希望这可以帮助


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(例如Post控制器)。

© www.soinside.com 2019 - 2024. All rights reserved.