Rails:用户使用以下命令销毁不相关的对象后退出:remote => true

我正在关注http://railscasts.com/episodes/250-authentication-from-scratch进行简单的身份validation。 它按预期工作。 我的应用程序中有一个模型,其中包含以下partial

   'Are you sure?', :method => :delete, :remote => true %>  

它在index.html.erb调用如下:

  @posts.reverse %> 

destroy.js.erb如下所示,如果对象被成功销毁则调用它。

 $('#').css('background', 'red'); $('#').hide(); 

单击delete按钮后, post对象将被正确删除, destroy.js.erb也会正确呈现。 但不知何故,用户已注销。 以下是我的posts_controller.rb的代码:

  def destroy logger.error 'in destroy' @post = Job.find(params[:id]) @post.destroy respond_to do |format| format.html { redirect_to(posts_url) } format.xml { head :ok } format.js end end 

任何线索为什么会出现这种行为?

并且,如果我从delete链接中删除:remote => true ,那么用户仍然登录。我在sessiondestroy方法中有日志语句,在任何一种情况下都不会被调用,但如果’ :remote=>true则会议以某种方式搞砸了。 在检查cookie时,我发现cookie没有被销毁但是当调用posts上的destroy方法时它会被修改。 不知道为什么会发生这种情况。

听起来你正在碰到一个铁路安全function,旨在防止跨站点请求伪造 。 添加:remote => true导致请求通过ajax提交而没有CSRF安全令牌,因此rails会破坏会话,因为它认为它是CSRF攻击。 要解决这个问题,您有以下几种选择:

  1. 快速而肮脏(且不安全)的解决方案是关闭该请求的安全检查。 为此,请将此行添加到控制器的顶部:

    skip_before_filter :verify_authenticity_token, :only => [:destroy]

  2. 更安全的解决方案是使用AJAX调用提交CSRF令牌。 我认为如果您将远程链接更改为button_to这将自动发生。 在这里阅读更多。

    <%= button_to 'Delete', post, :confirm => 'Are you sure?', :method => :delete, :remote => true %>

  3. 您还可以使用cookie来存储current_user而不是会话。 这对安全性的影响取决于您的应用程序的详细信息。