在添加第二个嵌套表单新字段时,第一个嵌套表单字段在编辑时消失

时间:2017-10-16 10:25:38

标签: ruby-on-rails

我有三张桌子

1)客户 2)家庭 3)emplyoee

在新表格中添加新字段时,完美无缺

但是如果我首先为家庭添加嵌套属性,则以编辑形式 然后我为员工添加嵌套属性,然后为家庭添加的字段消失,并为员工添加字段

        class Client < ActiveRecord::Base
         self.primary_key = "id"
         has_many :familys , dependent: :destroy, :foreign_key => 'client_id'
         accepts_nested_attributes_for :familys , allow_destroy: true
         has_many :employees , dependent: :destroy, :foreign_key => 'client_id'
         accepts_nested_attributes_for :employees , allow_destroy: true
        end


        class Family < ActiveRecord::Base
            belongs_to :client              
        end


        class Employee < ActiveRecord::Base
            belongs_to :client              
        end


       #-------_form.html.erb-----------------------------#

        <%= nested_form_for(@client) do |f| %>

        <div><%= f.submit 'addfamily',:name => "add_n_tenpo" %></div>

        <%= f.fields_for :familys  do |w| %>
         <tr>
            <td class="label_width">巡店店舗</td>
            <td><%= w.text_field :tenpo_code_1, class: 'form-control tenpoautofill' %></td>
            <td><%= w.text_field :tenpo_code_2, class: 'form-control tenpoautofill' %></td>
        </tr>
        <% end %>

        <div><%= f.submit 'addemployee',:name => "add_nw_tenpo" %></div>

        <%= f.fields_for :employees  do |nw| %>
        <tr>
              <td class="label_width">巡店店舗</td>
              <td><%= nw.text_field :nw_tenpo_code_1, class: 'form-control' %></td>
              <td><%= nw.text_field :nw_tenpo_code_2, class: 'form-control' %></td>
        </tr>
        <% end %>

        <% end %>

1 个答案:

答案 0 :(得分:0)

因为您需要以嵌套形式明确传递familysemployees的值以进行编辑操作,这不会影响您的新操作表单,因为在新操作中@client为零它需要为编辑操作传递值。

试试这个

<%= nested_form_for(@client) do |f| %>

    <%= f.fields_for :familys_attributes, @client.familys  do |w| %>
     <tr>
        <td class="label_width">巡店店舗</td>
        <td><%= w.text_field :tenpo_code_1, class: 'form-control tenpoautofill' %></td>
        <td><%= w.text_field :tenpo_code_2, class: 'form-control tenpoautofill' %></td>
    </tr>
    <% end %>

    <%= f.fields_for :employees_attributes, @client.employees  do |nw| %>
    <tr>
          <td class="label_width">巡店店舗</td>
          <td><%= nw.text_field :nw_tenpo_code_1, class: 'form-control' %></td>
          <td><%= nw.text_field :nw_tenpo_code_2, class: 'form-control' %></td>
    </tr>
    <% end %>

    <% end %>