我有三个表
1) 客户2) 家庭3) 雇员
虽然以新形式添加新字段,但一切都很完美
但是在编辑形式中,如果我首先为家庭添加嵌套属性然后我为员工添加嵌套属性,然后为家庭添加的字段消失,为员工添加字段
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 %>
因为您需要显式传递familys
的值,并以嵌套形式employees
进行编辑操作,所以这不会影响新操作的形式,因为在新操作中@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 %>