ruby-on-rails - Ajax 发布点击 Action ,无需使用 CanCan 和 Devise 进行身份验证

标签 ruby-on-rails ruby jquery devise cancan

我正在使用 Cancan 来授权我的评论资源并设计进行身份验证。我有以下 Controller ,当我没有使用设计登录并尝试发布新评论时,用户将被重定向到登录页面(new_user_session_path),因为他们必须登录才能创建评论。但是,如果我在未登录的情况下使用 remote: true 发布新评论,它会通过呈现 create.js.erb 并在Chrome 控制台在解析 @comments.any? 时出错,应该是 nil。但是,如果用户尚未登录但想提交评论,我想获得类似 :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

最佳答案

我会修改你的 Controller :

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 消息。

关于ruby-on-rails - Ajax 发布点击 Action ,无需使用 CanCan 和 Devise 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14372333/

相关文章:

ruby-on-rails - 部署为 .war 文件时如何处理 Rails 中的上传和日志?

ruby - 我应该对小型单一服务服务器采取安全措施吗?

javascript - 这是使用 jQuery 解析 XML 时的错误吗?

javascript - 如何使移动 <select> 允许键入选项而不是选择一个选项。

ruby-on-rails - rspec 测试 has_many :through and after_save

ruby-on-rails - 如果我使用 will_paginate gem,mongo 查询是否仍然选择所有行然后分页?

ruby-on-rails - 如何检查 Rails 迁移中的数据库类型?

html - 遍历所有 <dd> 标签并通过 Mechanize/Nokogiri 提取特定信息

jquery - 移动 map 中心而不删除标记(Google map v. 3.0)

ruby-on-rails - Ensure_inclusion_of 在应该失败的时候仍然通过?