如何为访客用户正确配置Devise + Cancan
在Rails 3.2应用程序中,我使用的是Devise + CanCan。 该应用程序以前仅限制登录用户的访问权限。 我正在添加一个Guest用户/能力,可以阅读该网站的某些部分。
我无法理解设置它的“正确”方法,特别是before_filter :authenticate!
组合before_filter :authenticate!
控制器中需要load_and_authorize_resource
。
在努力实现这一目标时,我已将能力等级降至最低。
#Ability.rb class Ability include CanCan::Ability def initialize(user_or_admin) user_or_admin ||= User.new can :manage, :all end end
在无模型/静态页面Home控制器中
#home_controller.rb class HomeController < ApplicationController load_and_authorize_resource def index ...some stuff end end
和
#application_controller.rb class ApplicationController < ActionController::Base protect_from_forgery before_filter :authenticate! ...more stuff end
通过此设置,未登录的用户将被重定向到Devise登录页面。
如果我删除before_filter :authenticate!
从应用程序控制器我从activesupport-3.2.11/lib/active_support/inflector/methods.rb
得到一个错误uninitialized constant Home
如果我从家庭控制器中删除load_and_authorize_resource
,则此错误消失。
这对我的简化测试能力类来说没问题,但是当我开始添加角色和能力时,我需要让CanCan处理Home控制器,即需要load_and_authorize_resource
。
任何人都可以帮助我理解为什么在before_filter :authenticate!
时发生这个错误before_filter :authenticate!
被移除,并指向我解释为访客用户设置Devise + Cancan的“正确”方法的任何信息。 到目前为止我发现的信息只解释了如何设置Ability类,而不是如何配置Devise。
问题是没有资源可以授权。 因此,您只需要调用authorize_resource
而不是load_and_authorize_resource
。 有关详细信息,请参阅在cancan文档中授权控制器操作 。
更新:您还必须将类指定为false: authorize_resource class: false
。
然后您的家庭控制器将如下所示:
class HomeController < ActionController::Base authorize_resource class: false def show # automatically calls authorize!(:show, :home) end end
此信息位于非RESTful控制器部分中 。 对于那个很抱歉。