【问题标题】:Ajax posting hitting action without authentication with CanCan And DeviseAjax 发布点击动作,无需使用 CanCan 和 Devise 进行身份验证
【发布时间】:2012-12-31 14:15:06
【问题描述】:

我正在使用 Cancan 来授权我的 cmets 资源并设计进行身份验证。我有以下控制器,当我没有使用 devise 登录并尝试发布新评论时,用户将被重定向到登录页面(new_user_session_path),因为他们必须登录才能创建评论。但是,如果我在未登录的情况下使用remote: true 发布新评论,则通过呈现create.js.erb 并在Chrome 控制台中使用html 响应并在解析@comments.any? 时出现错误,它正在执行操作,这应该是零。但是,如果用户尚未登录但想提交评论,我想获得类似 :unauthorized 或 501 的状态代码,因此我可以使用 jQuery 捕获它并调出登录表单。我认为gem cancan 提供的load_and_authorize_resource 会阻止我的请求甚至无法执行操作,但显然事实并非如此。我应该怎么做才能获得状态响应而不是采取行动?谢谢!

class CommentsController < ApplicationController
  load_and_authorize_resource
  #should I also add a devise authenticate_user! before filter here?

  def create
    @commentable = find_commentable
    @comment = current_user.comments.build(params[:comment].merge(:commentable => @commentable))
    if @comment.save
      respond_to do |format|
        format.html { redirect_to @commentable, :notice => "Successfully created comment."}
        format.js   {@comments = @commentable.comments}
      end
    else
      respond_to do |format|
        format.html { redirect_to @commentable, :notice => "Comment NOT created."}
        format.js   { render :status => :internal_server_error }
      end
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby jquery devise cancan


    【解决方案1】:

    我会将您的控制器修改为:

    class CommentsController < ApplicationControlle
    
      def create
        @commentable = find_commentable
        authorize! :create, @commentable
        @comment = current_user.comments.build(params[:comment].merge(:commentable => @commentable))
        if @comment.save
          respond_to do |format|
            format.html { redirect_to @commentable, :notice => "Successfully created comment."}
            format.js   {@comments = @commentable.comments}
          end
        end
      end
    end
    

    如果您的用户已获得授权,则会出现您的成功消息。否则,当未经授权的用户尝试发表评论时,将出现 501 消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多