[英]Cannot access action in Rails even with CanCanCan ability
I have the following: 我有以下内容:
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
I confirmed the user is content_creator
. 我确认用户为
content_creator
。 I even restarted the server. 我什至重启了服务器。 The user can update a
Unit
. 用户可以更新
Unit
。 They cannot view the index of questions in that unit however. 但是,他们无法查看该单元中的问题索引。 Why not?
为什么不?
If I put can :manage, Question
at the beginning of ability.rb
, then it is still unauthorized. 如果我在
ability.rb
的开头放置can :manage, Question
,那么它仍然是未授权的。 If I use can :manage, :all
, then it works. 如果我使用
can :manage, :all
,那么它可以工作。
Cancancan ~> 1.10 Cancancan〜> 1.10
I got rid of 我摆脱了
# authorize! :view_all, @questions # prevents ContentCreators from viewing /units/1/questions
And changed 并改变了
can :read, Question
To 至
can :show, Question
Everywhere else in ability.rb
so only authorized viewers can see the index. 在其他地方
ability.rb
所以只有被授权的观众可以看到指数。 This isn't a full answer however because it's still not clear why the original code did not work. 但是,这并不是一个完整的答案,因为仍然不清楚为什么原始代码无法正常工作。
I was also in a similar situation, after looking around what I found is this: 环顾四周后,我也遇到了类似情况:
class ProductsController < ActionController::Base
load_and_authorize_resource
def discontinue
# Automatically does the following:
# @product = Product.find(params[:id])
# authorize! :discontinue, @product
end
end
according to the commented out text, cancancan by default expect the action name to equal the ability, in your case you'll have to create a new action called 根据注释文字,默认情况下,cancancan期望动作名称等于该功能,在这种情况下,您必须创建一个新动作,称为
def view_all
def view_all
or else you'll have to create a sub rule for index. 否则,您将必须为索引创建一个子规则。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.