I have three tables
1) client 2) family 3) emplyoee
While adding new fields in new form everthing works perfect
But in edit form if i add nested attributes for family first and then i add nested attributes for employee then the fields added for family are gone and fields are added for employee
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 %>
Because You need to explicitly pass values for familys
and employees
in nested form for edit action, this doesn't effect your new action's form because in new action @client
is nil so it need to pass value for edit action.
Try this
<%= 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 %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.