【问题标题】:Devise+CanCan strange behaviour when deletingDevise+Can 删除时会出现奇怪的行为
【发布时间】:2011-12-08 19:12:03
【问题描述】:

我已经通过 CanCan 设计和管理角色权限实现了身份验证。我的应用程序管理食谱,当我销毁食谱时,我关闭会话并将我重定向到登录视图...

如果我不检查身份验证和权限(请参阅上面的 recipes_controller),它可以正常工作。

这很奇怪,我不知道为什么会这样。请帮忙。

谢谢

日志:

 Started POST "/recipes/21" for 127.0.0.1 at Thu Dec 08 19:53:30 +0100 2011
 Processing by RecipesController#destroy as HTML
 Parameters: {"id"=>"21"}
 User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 5 LIMIT 1
 Completed 401 Unauthorized in 44ms

 Started GET "/users/sign_in" for 127.0.0.1 at Thu Dec 08 19:53:30 +0100 2011  
 Processing by Devise::SessionsController#new as HTML
 Rendered devise/shared/_links.erb (2.5ms)
 Rendered devise/sessions/new.html.erb within layouts/application (14.2ms)
 Completed 200 OK in 52ms (Views: 20.8ms | ActiveRecord: 0.0ms)

RECIPES_CONTROLLER:

class RecipesController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource

def destroy
    @recipe = Recipe.find(params[:id])
    @recipe.destroy
    redirect_to recipes_url, :notice => "Successfully destroyed Recipe."
end

能力:

class Ability
include CanCan::Ability

def initialize(user)
    user ||= User.new # guest user
    if user.role? :super_admin
        can :manage, :all
    else if user.role? :super_read_admin
        can :read, :all
    else
        # manage reciped he owns
        can :manage, Recipe do |recipe|
        recipe.owner == user
    end
end
end
end
end

【问题讨论】:

    标签: ruby-on-rails devise cancan


    【解决方案1】:

    回答,每个提问者(见下面的 cmets)

    您必须确保在布局中包含 &lt;%= csrf_meta_tags %&gt;

    =============================

    (原回复)

    Completed 401 Unauthorized in 44ms 看来,您的用户不允许销毁此配方。检查recipe.owner.id 是否为 5...

    在控制台中试试这个:

    user = User.find(5)
    puts user.role
    ability = Ability.new(user)
    ability.can? :destroy, Recipe.find(21)
    

    第二个和最后一个命令的输出是什么?

    【讨论】:

    • 查看答案更新:在 cmets 中编写代码可读性不强...让我知道输出。
    • 不确定您是否期待我的回答...第二个命令对我不起作用,但如果我输入“puts user.role?:super_admin”,它会显示 True。最后一个命令说 True。如果用户无权销毁配方,应用程序将不会关闭设计会话
    • 如果你注释掉load_and_authorize_resource一切正常?
    • 如果我同时评论 load_and_authorize_resource 和 before_filter :authenticate_user!,它可以正常工作。如果我只评论 before_filter:authenticate_user!我有:'Completed 500 Internal Server Error in 105ms' 而不是错误 401
    • 但是如果你只评论 load_and_authorize_resource 呢?
    猜你喜欢
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    • 2017-11-20
    • 2013-10-04
    相关资源
    最近更新 更多