簡體   English   中英

即使具有CanCanCan能力也無法訪問Rails中的動作

[英]Cannot access action in Rails even with CanCanCan ability

我有以下內容:

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 但是,他們無法查看該單元中的問題索引。 為什么不?

如果我在ability.rb的開頭放置can :manage, Question ,那么它仍然是未授權的。 如果我使用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

否則,您將必須為索引創建一個子規則。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM