用于多个对象的单一形式的复选框

时间:2017-12-11 21:51:46

标签: ruby-on-rails

在尝试创建单个表单以添加多个对象时,我按照本教程进行操作。问题是,我只能输入字符串属性的值而不能输入布尔属性,因为它会使参数混乱。我的表格哪里出错了? http://vicfriedman.github.io/blog/2015/07/18/create-multiple-objects-from-single-form-in-rails/

<%= form_tag boa_constrictors_litter_hash_path do %>
  <% @litter.each do |snake| %>
    <%= fields_for 'offspring[]', snake do |f| %> 
        <%= f.hidden_field :type, :value => "BoaConstrictor" %>
        <%= f.text_field :name, placeholder: "Name"%>
        <%= f.label :gender %>
        <%=f.select :gender, options_for_select([['Male', 'Male'], 
            ['Female', 'Female']]) %>
        <%= f.hidden_field :year, :value => "2017" %>
        <%= f.label :available %>
        <%= f.check_box :available %>
        <%= f.label :private %>
        <%= f.check_box :private %>
        <%= f.label "Notes" %>
        <%= f.text_field :notes %>
        <% if @dame.hypo? or @sire.hypo? %>
            <%= f.label "Hypo" %>
            <%= f.check_box :hypo %>
        <% end %>
        <% if @dame.img? or @sire.img? %>
            <%= f.label "IMG" %>
            <%= f.check_box :img %>
        <% end %>   
    <% end %><br>
<% end %>    
<%= submit_tag %>

实施例;创建两个蛇,一个名为“first”w / available:true,另一个名为“second”,发送以下参数,创建三条具有不正确属性的蛇:

"offspring"=>[{"type"=>"BoaConstrictor", "name"=>"first", "gender"=>"Male", 
"year"=>"2017", "available"=>"0"}, {"available"=>"1", "private"=>"0", 
"notes"=>"", "hypo"=>"0", "img"=>"0", "type"=>"BoaConstrictor", 
"name"=>"second", "gender"=>"Male", "year"=>"2017"}, {"available"=>"0", 
"private"=>"0", "notes"=>"", "hypo"=>"0", "img"=>"0"}], "commit"=>"Save 
changes"}

如果我进入了两只动物,一只名为“first”,音符为“works”,另一只名为“second”,音符为“now”,它会给出正确的参数并正确创建两只动物。

"offspring"=>[{"type"=>"BoaConstrictor", "name"=>"first", "gender"=>"Male", 
"year"=>"2017", "available"=>"0", "private"=>"0", "notes"=>"works", 
"hypo"=>"0"}, {"type"=>"BoaConstrictor", "name"=>"second", "gender"=>"Male", 
"year"=>"2017", "available"=>"0", "private"=>"0", "notes"=>"now", 
"hypo"=>"0"}], "commit"=>"Save changes"}

如果我检查表格中的任何布尔值,那么params会对该属性进行切割并重复导致无关的对象并弄乱后面任何对象的属性。

解决 Check_box无法正确处理数组中的属性,如下所示:https://apidock.com/rails/ActionView/Helpers/FormHelper/check_box

解决方案是使用check_box_tag 使用&lt;%= check_box_tag'offspring [] [private]'%&gt;而不是&lt;%= f.check_box:private%&gt;工作正常。

1 个答案:

答案 0 :(得分:0)

check_box无法正确记录数组中的属性here

解决方案是使用check_box_tag
而不是<%= f.check_box :private %>
使用<%= check_box_tag 'offspring[][private]' %>工作正常。

相关问题