Rails 4删除按钮将我注销并导致"无法验证CSRF令牌真实性"

Rya*_*son 5 ruby-on-rails devise ruby-on-rails-4

我正在运行Rails 4.2,Devise 3.4.1和CanCan 1.6.10.当我尝试通过标准删除按钮删除资源时,如下所示,我退出并重定向到登录页面.

<a data-confirm="Are you sure?" class="btn-alert" rel="nofollow" data-method="delete" href="/admin/lots/6">Delete</a>

我的开发日志告诉我这是因为它"无法验证CSRF令牌的真实性".我似乎能够让它工作的唯一方法是从删除按钮更改为发布到删除操作的表单,但这有点愚蠢.我在其他Rails 4应用程序中完成了这个,所以我很确定我做得对.

index.html.erb

<% if can? :destroy, lot %>
   <%= link_to "Delete", admin_lot_path(lot.id), method: :delete, data: {confirm: "Are you sure?"}, class: 'btn-alert' %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

lots_controller.rb

class Admin::LotsController < ApplicationController
  before_filter :authenticate_user!
  load_and_authorize_resource

  def destroy
    @lot.destroy
    redirect_to admin_lots_path, notice: "Lot was successfully removed."
  end
end`
Run Code Online (Sandbox Code Playgroud)

就像我说的那样,用表格替换按钮似乎有效,但这并不理想.

<%= form_for([:admin, lot], method: :delete) do |f| %>
   <%= f.submit value: "Delete", class: 'btn-standard', data: {confirm: "Are you sure?"} %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

如果我注释掉before_filter :authenticate_user!,并load_and_authorize_resource从控制它的工作原理.我假设csrf令牌不会像这样在表单中一起发送.

有没有人对我能尝试什么有任何想法?如果它有用,愿意发布更多代码.这发生在我的应用程序btw中的所有删除.

更新:这是来自development.log的片段

Started DELETE "/admin/lots/6" for 127.0.0.1 at 2015-05-26 15:03:22 -0500
Processing by Admin::LotsController#destroy as HTML
  Parameters: {"id"=>"6"}
Can't verify CSRF token authenticity
Run Code Online (Sandbox Code Playgroud)

Zek*_*Zek 8

button_to而不是link_to.

button_to "Delete", admin_lot_path(lot.id), method: :delete, data: {confirm: "Are you sure?"}, class: 'btn-alert'
Run Code Online (Sandbox Code Playgroud)

link_to 生成这个缺少真实性令牌的HTML,

<a data-confirm="Are you sure?" class="btn-alert" rel="nofollow" data-method="delete" href="/admin/lots/6">Delete</a>
Run Code Online (Sandbox Code Playgroud)

button_to产生

<form class="button_to" method="post" action="/admin/lots/6">
    <input type="hidden" name="_method" value="delete">
    <input data-confirm="Are you sure?" class="btn-alert" type="submit" value="Delete">
    <input type="hidden" name="authenticity_token" value="1QajBKKUzoEtUqi6ZX8DsQtT9BfvKY/WVXAr4lu4qb+iLGMkLlsviNcctlGxyq+VrsMa+U9vmb4PAdaRFDKZVQ==">
</form>
Run Code Online (Sandbox Code Playgroud)

  • Ryan,你的`head`标签中有`= csrf_meta_tags`吗?_(编辑:我意识到你确实在上面引用了它.我很确定在Rails 4中仍然需要jQuery UJS在非GET请求上发送真实性令牌.)_ (3认同)