![](/img/trans.png)
[英]Rails 3 - CanCan error? NameError (uninitialized constant Ability::Invitation):
[英]Rails3 - CanCan - uninitialized constant Ability::Page
我剛剛將cancan 1.5.0添加到我的rails 3應用程序這里是我的能力文件 -
def initialize(user)
user ||= User.new
if user.role == 'Admin'
can :manage, :all
end
if user.role == 'Standard'
can :manage, Library
can :manage, Page
else
can :manage, Page
can :manage, Library
end
我有一個自定義類(非restful函數)
class PagesController < ApplicationController
authorize_resource :class => false
def home
end
end
正如你所看到的,我正在使用正確的函數來安排一個不太安寧的類,但我仍然遇到這個錯誤 -
uninitialized constant Ability::Page
這是堆棧跟蹤的開始 -
app/models/ability.rb:16:in `initialize'
cancan (1.5.0) lib/cancan/controller_additions.rb:327:in `new'
cancan (1.5.0) lib/cancan/controller_additions.rb:327:in `current_ability'
cancan (1.5.0) lib/cancan/controller_additions.rb:308:in `authorize!'
cancan (1.5.0) lib/cancan/controller_resource.rb:40:in `authorize_resource'
cancan (1.5.0) lib/cancan/controller_resource.rb:9:in `block in add_before_filter'
activesupport (3.0.3) lib/active_support/callbacks.rb:436:in ` _run__1386450187816505438__process_action__15559788756486462__callbacks'
activesupport (3.0.3) lib/active_support/callbacks.rb:409:in `_run_process_action_callbacks'
activesupport (3.0.3) lib/active_support/callbacks.rb:93:in `run_callbacks'
謝謝,亞歷克斯
CanCan文檔將can
方法描述為:
can
方法用於定義權限並需要兩個參數。 第一個是您正在設置權限的操作,第二個是您正在設置它的對象類。
因此,問題是您的系統中沒有用於CanCan管理訪問權限的Page
類。
請注意,CanCan的構建如下:(重點由我添加)
授權庫,Ruby on Rails的制約哪些資源給定用戶被允許訪問。
因此,如果您的目標是控制沒有附加rails資源的抽象概念,那么CanCan可能會遇到困難
只是給現在發現這個的人的一個注釋......
您可以授權任何非寧靜的控制器,抽象類和方法。
例:
/app/models/role_ability.rb
class RoleAbility
def initialize(user)
user ||= User.new
if user.role == 'Admin'
can :manage, Post # some existing resource_authorisation
can :do_this, :on_this # authorizing a non resource
end
end
end
:do_this和:on_this完全是任意的,但它們必須匹配授權! 控制器中的參數如此......
class Controller < ApplicationController
def some_abstract_method
### Awesome method code goes here
authorize! :do_this, :on_this
end
end
請記住,您可能已經在ApplicationController中發生了一些資源授權,可能就是這樣
class ApplicationController
authorize_resource || authorize! :admin, Object || load_and_authorize_resource etc
end
所以請記住在非寧靜/抽象控制器中使用skip_authorize_resource
class AbstractController < ApplicationController
skip_authorize_resource
def some_abstract_method
authorize! :do_this, :on_this
end
end
現在管理員可以:do_this,:on_this並且將很好地授權。 你可能想要在語義上更具名稱,只是想強調任意性。
這都是使用Cancan 1.5,之前沒有嘗試過。
來自https://github.com/ryanb/cancan/wiki/Non-RESTful-Controllers
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.