如何显示未经授权的罐头可以访问的错误 [英] How do I show an error for unauthorized can can access

查看:77
本文介绍了如何显示未经授权的罐头可以访问的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Bootstrap,它的div class="alert notice"包含一堆用于各种通知消息的类.

I am using Bootstrap, which has div class="alert notice" that has a bunch of classes for various notice messages.

我还添加了AJAX销毁操作以进行评论,并在其中添加了cancan授权.当我尝试删除无法访问current_user的评论时,它是行不通的-正确.

I also have an AJAX destroy action for a comment, that I have added cancan authorization on. When I try to delete a comment that the current_user doesn't have access to it doesn't work - which is correct.

但是我想发生的是在Bootstrap样式的div中弹出错误消息5-10秒,然后消失.

But what I want to happen is for an error message to pop-up, in a Bootstrap style'd div for 5 - 10 seconds and then disappear.

这是我CommentsController.rb

  def destroy
    respond_to do |format|
      if @comment.destroy
          format.html { redirect_to root_url, notice: 'Comment was successfully deleted.'  }
          format.json { head :no_content }
          format.js   { render :layout => false }      
      else
          format.json { render json: @comment.errors, status: :unprocessable_entity }  
      end
    end        
  end

在同一控制器的私有方法中设置了@comment的位置:

Where I have the @comment set in a private method in the same controller:

  private
    def set_comment
      @comment = current_user.comments.find(params[:id])
    end

这是我的comments/destroy.js.erb

$('.delete_comment').bind('ajax:success', function() {  
        $(this).closest('div#new_comment').fadeOut();
});  

但这不会影响未经授权的访问.

But that doesn't affect unauthorized access.

在我的ability.rb中,我有这个:

can :manage, Comment, user_id: user.id

当我尝试删除我无权访问的评论时,在我的日志中:

In my log when I try to delete a comment that I don't have access to, I get this in my log:

Started DELETE "/comments/5" for 127.0.0.1 at 2014-10-16 02:56:53 -0500
Processing by CommentsController#destroy as JS
  Parameters: {"id"=>"5"}
  User Load (0.4ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1
  FamilyTree Load (0.2ms)  SELECT  "family_trees".* FROM "family_trees"  WHERE "family_trees"."user_id" = $1 LIMIT 1  [["user_id", 1]]
  ReadMark Load (0.1ms)  SELECT  "read_marks".* FROM "read_marks"  WHERE "read_marks"."user_id" = $1 AND "read_marks"."readable_type" = 'PublicActivity::ORM::ActiveRecord::Activity' AND "read_marks"."readable_id" IS NULL  ORDER BY "read_marks"."id" ASC LIMIT 1  [["user_id", 1]]
  Comment Load (0.3ms)  SELECT  "comments".* FROM "comments"  WHERE "comments"."user_id" = $1 AND "comments"."id" = $2 LIMIT 1  [["user_id", 1], ["id", 5]]
Completed 404 Not Found in 8ms

ActiveRecord::RecordNotFound - Couldn't find Comment with 'id'=5 [WHERE "comments"."user_id" = $1]:

那是完美的.

我要做的就是在Bootstrap警报中显示适当的错误,该错误会在几秒钟后消失.

All I want to do is show an appropriate error in a Bootstrap alert that disappears in a few seconds.

我该怎么做?

推荐答案

首先,如果您使用cancan-只需使用cancan:

For the first, if you use cancan - just use cancan:

#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
  load_and_authorize_resource #this will set @comment by your ability and authorize action
  ...
end

这将引发CanCan::AccessDenied而不是ActiveRecord::RecordNotFound错误.

让我们用救援_来自

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  ...
  rescue_from CanCan::AccessDenied do |exception|
    @error_message = exception.message
    respond_to do |f|
      f.js{render 'errors/error', status: 401}
    end
  end
end

对于弹出式通知,我使用PNotify库 http://sciactive.github.io/pnotify/ 它将在右上角显示错误,然后隐藏. 只要将其包含在您的项目中,您就可以显示如下错误:

For popup notifications I use PNotify library http://sciactive.github.io/pnotify/ It will show error in top right conner and then hide. Just include it in your project and you can show the errors like this:

#app/views/errors/error.js.erb
new PNotify({
  title: 'Oh No!',
  text: '<%=@error_message%>',
  type: 'error'
});

此代码使您避免避免错误举报ActiveRecord::RecordNotFound错误.

This code lets you avoid of catching ActiveRecord::RecordNotFound error as of bad practice.

更新

我忘记了一些东西!您必须删除set_comment方法和before_action或这样写:

I forgot something! You have to remove set_comment method and before_action or write it like this:

before_action :set_comment
...
private
def set_comment
  @comment ||= current_user.comments.find(params[:id])
end

此回调覆盖了代码中load_and_authorize_resource中的@comment变量. Cancan不需要此帮助程序,因为它通过load_and_authorize_resource

This callback overwrote @comment variable from load_and_authorize_resource in your code. Cancan makes this helper unneeded because it loads resource by load_and_authorize_resource

UPDATE2

您还需要确保您正在 CanCanCommunity 中使用最新版本的cancan和rails4. >,因为原始的旧版本不支持rails4

You also need to make sure that you are using the latest version of cancan with rails4 from CanCanCommunity because original old version doesn't support rails4

只需在您的Gemfile中使用它

Just use this in you Gemfile

gem 'cancancan', '~> 1.9'

代替

gem 'cancan'

这篇关于如何显示未经授权的罐头可以访问的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆