我正在使用 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/