【发布时间】: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