我有以下内容:
questions_controller.rb
class QuestionsController < ApplicationController
load_and_authorize_resource #cancancan
def index
authorize! :view_all, @questions
ability.rb
class Ability
include CanCan::Ability
def initialize(user)
...
elsif user.content_creator
can [:index, :read, :create, :update], Unit
can [:index, :read, :create, :update, :view_all], Question
routes.rb
resources :units do
resources :questions, only: [:index]
Log
Started GET "/units/1/questions" for ::1 at 2018-10-29 13:37:15 -0400
Processing by QuestionsController#index as HTML
Parameters: {"unit_id"=>"1"}
User Load (8.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 13]]
You are not authorized to access this page.
Redirected to http://localhost:3000/dashboard
我确认用户是content_creator
。我甚至重新启动了服务器。用户可以更新Unit
。但他们无法查看该单位的问题索引。为什么不?
如果我把can :manage, Question
放在ability.rb
的开头,那么它仍然是未经授权的。如果我使用can :manage, :all
,那么它的工作原理。
Cancancan~> 1.10
我摆脱了
# authorize! :view_all, @questions # prevents ContentCreators from viewing /units/1/questions
并改变了
can :read, Question
至
can :show, Question
在ability.rb
的其他地方,只有授权的观众才能看到索引。这不是一个完整的答案,因为它仍然不清楚为什么原始代码不起作用。
在环顾四周我发现的情况后,我也处于类似情况:
class ProductsController < ActionController::Base
load_and_authorize_resource
def discontinue
# Automatically does the following:
# @product = Product.find(params[:id])
# authorize! :discontinue, @product
end
end
根据注释掉的文字,cancancan默认期望动作名称等于能力,在你的情况下你必须创建一个叫做的新动作
def view_all
否则你将不得不为索引创建一个子规则。
希望这可以帮助。