如何在rails中发布对象数组?

时间:2016-12-31 19:32:51

标签: ruby-on-rails ruby forms

我的

中有以下代码
  

new.html.erb

    <%= form_tag puppies_path do %>
        <% @kennel.each do |puppy| %>
            <%= fields_for 'puppies[]', puppy do |p| %>
                <div class="field">
                    <%= p.label :name %><br>
                    <%= p.text_field :name %>
                </div>

                <div class="field">
                    <%= p.label :breed %><br>
                    <%= p.text_field :breed %>
                </div>
            <% end %>
        <% end %>
        <div class="actions">
            <%= submit_tag %>
        </div>
    <% end %>

而puppies []数组变量,应该将对象数组发布到控制器,只发布单个对象。请帮助将数组发布到控制器。提前谢谢!

2 个答案:

答案 0 :(得分:0)

fields_for的常规设置是这样的。

<% @kennel.each do |kennel| %>
  <%= fields_for :puppies, @kennel.puppies do |p| %>

答案 1 :(得分:0)

是的,我刚刚找到答案......

  

在new.html.erb文件中

    <%= form_tag puppies_path do %>
        <% 2.times do %>
            <%= render 'puppies_group_form' %><br>    
        <% end %>
        <%= submit_tag "Submit" %>
    <% end %>
  

在_puppies_group_form

    Name <%= text_field_tag "puppies[][name]" %>
    Breed <%= text_field_tag "puppies[][breed]" %>