2012-07-10 54 views
1

我正在構建一個site-wide cancan auth系統。只是爲了讓我的嘗試很簡單的驗證,我初始化每次我試圖打一個頁面時,我的測試用例:Cancan具有數據庫角色和功能:AuthorizationNotPerformed

# application_controller.rb 
class ApplicationController < ActionController::Base 
    admin = Role.new(name: :admin, is_default: true) 
    admin.permissions << Permission.create(action: :manage, subject_class: :all) 
    admin.save 
    current_user=User.create! 
    # users automatically get associations to all roles with `is_default: true` 

    check_authorization 
end 

skip_authorization_check只有控制器讓我通過,其他所有拋出AuthorizationNotPerformed錯誤:

CanCan::AuthorizationNotPerformed in ExampleAuthEngin::PermissionsController#index 

This action failed the check_authorization because it does not authorize_resource. Add skip_authorization_check to bypass this check. 

我在做什麼錯?

回答

3

內的控制器,你需要或者致電load_and_authorize_resource(在類級別),或在個人行動呼籲authorize! :action, resource其中:actionresource是要測試的東西。 load_and_authorize_resource將before_filters添加到爲資源實例化實例變量的控制器(其中實例化方法基於操作,並且要加載的資源基於控制器名稱),並且還添加了一個過濾器來授權已加載的資源,授權基於正在被擊中的動作,可以是:read,:create,:update或destroy。

您可以閱讀更多關於它here

+0

那麼,這有很大的幫助。基於[check_authorization'方法文檔的措辭](https://github.com/ryanb/cancan/#4-lock-it-down),我認爲'load_and_authorize_resource'假設所有模型沒有'skip_authorization_check '。現在我的模型屬性和路線正在工作,並且我可以研究(當前非常糟糕的)模型方法和控制器邏輯。謝謝! – 2012-07-10 23:27:48

+0

沒有問題。 :)非常酷,你把它放在引擎中。這是我的團隊想到要做的事情。如果你開源,我相信會有強烈的需求。 – Adam 2012-07-10 23:45:18

+0

我已經爲我目前的項目獲得了足夠的骨骼。還有更多的項目將與我們一起構建,所以一旦它達到了無法確定的複雜程度,我們將追蹤這篇文章,並指出您的看法。 :) – 2012-07-13 03:44:35