【问题标题】:Reformat a form_tag to form_for to use formaction将 form_tag 重新格式化为 form_for 以使用 formaction
【发布时间】:2017-02-10 02:02:19
【问题描述】:

我的edit 视图中有一个form_tag

<%= form_tag stage_batch_path(@stage_batch), multipart: true, class: 'form-inline', role: 'form', method: :put do %>
  <div class="form-group">
    <%= label_tag 'csv_batch_file', 'Select batch file' %>
    <%= file_field_tag 'csv_batch_file', class: 'form-control' %>
  </div>
  <br>
  <div class="form-group">
    <%= label_tag 'potential_item_id', 'Input item id' %>
    <%= text_field_tag "potential_item_id" %>
  </div>
  <br>
  <%= button_tag 'Stage', class: 'btn btn-primary' %>
<% end %>

目前 puts 到 stage_batches/:id 这是我想要的。

但是,我想将posts 的另一个按钮添加到其他控制器,例如Foo#create。我在another answer 中读到formaction 选项将起作用。但是给定的示例使用form_for 而不是form_tag

<% form_for(something) do |f| %>
    ...
    <%= f.submit "Create" %>
    <%= f.submit "Special Action", formaction: special_action_path %>
<% end %>

如何将我的form_tag 重写为form_for

【问题讨论】:

    标签: ruby-on-rails forms ruby-on-rails-4


    【解决方案1】:
    <%= form_tag stage_batch_path(@stage_batch), multipart: true, class: 'form-inline', role: 'form', method: :put do %>
    

    ==>

    <%= form_for @stage_batch, url: stage_batch_path(@stage_batch), multipart: true, class: 'form-inline', role: 'form', method: :put do |f|%>
    

    也同:

    <%= form_for @stage_batch, class: 'form-inline' do |f|%> #if @stage_batch is new_record? then method: :post, else method: :put
    

    PS:你应该试试这个https://github.com/plataformatec/simple_form,救命稻草。

    使用 simple_form,您的表单可以转换为:

    <%= simple_form_for @stage_batch do |f|%>
      <%= f.input :csv_batch_file, as: :file %>
      <%= f.input :potential_item_id %>
      <%= f.submit 'stage' %>
    <%end%>
    

    简单而美丽。

    【讨论】:

    • 您能否添加一个使用simple_form 的示例,并将PUTPOST 从同一表单提交到不同的路由?
    • 但是如何将表单提交到两种不同的路径之一?说Foo#createBar#edit
    • form_for & simple_form_for 生成的表单遵循 RESTful 规则,即提交 object.new 到 [object_path(object), method::post] 和 object.edit 到 [object_path(object), method: :放]。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多