Rails remote form collection_select onchange error



我试图在更改选择选项时自动提交远程表单。当我从表单标签中删除remote: true时,一切都可以,除了我不希望每次重新加载页面。

我正在使用Rails 5.1.4。

代码

<%= form_for @foo, remote: true do |f| %>
    ... fields
    <%= f.collection_select :bar_id, @list, :id, :name,
       {include_blank: '-'}, { onchange: 'this.form.submit();'} %>
<% end %>

控制器

def update
  respond_to do |format|
    if @foo.update(foo_params)
      format.html { redirect_to @foo }
      format.json { render :show, status: :ok, location: @foo }
    else
      format.html { render :edit }
      format.json { render json: @foo.errors, status: :unprocessable_entity }
    end
  end
end

在视图中更新选择时,我会遇到以下错误:

ActionController :: InvalideUthenticityToken

我假设this.form.submit();是问题所在。我如何获得此表格成功提交?

尝试以以下简单的方式将authenticity_token: true添加到您的表单标签中,如

<%= form_for @foo, remote: true, authenticity_token: true do |f| %>

它应该起作用,至少对我工作。

在注释后更新

如果您使用remote: true,则需要与部分合作,例如您在new.html.erb中的表格,然后切出形式的部分并为_form.html.erb之类的表格创建部分,然后将其渲染到new.html.erb中,例如

new.html.erb

<div id="my-form">
   <%= render partial: "form" %>
</div>

和基于 new.js.erb之类的主文件创建js.erb文件,然后将此行如

一样放置
$("#my-form").html("<%= escape_javascript(render("form")) %>");

在您的控制器上添加 format.js,如下

format.html { redirect_to @foo } 
format.js 
format.json { render :show, status: :ok, location: @foo }

有关使用ROR-5参考的完整jQuery/AJAX您可以阅读本教程,这将有助于刷取您的jQuery/AJAX技能

希望能起作用

将此行添加到您的表格中。

<%= tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) %>

您的表格应该是这样:

   <%= form_for @foo, remote: true do |f| %>
        <%= tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) %>
        ... fields
        <%= f.collection_select :bar_id, @list, :id, :name,
           {include_blank: '-'}, { onchange: 'this.form.submit();'} %>
    <% end %>

真实性令牌是您视图中生成的随机值,以证明请求是从您的网站上的表单而不是其他地方提交的。这可以防止CSRF攻击

您可以通过两种方式避免上述错误

1(在应用程序控制器中添加以下代码

skip_before_filter :verify_authenticity_token  

参考链接:http://api.rubyonrails.org/classes/actioncontroller/requestforgeryprotection/classmethods.html

2(添加 authenticity_token以表格

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

<%= csrf_meta_tags %>

最新更新