我的任务是将多个模型集成到一个表单中。我有一个表单“注册”和两个模型buyer
和address
。但是通过这样做,我不能将两个表格附加在一起。
_form.html.erb
是
<% @register.buyers.build %>
<%= form_for(@register) do |f| %>
<% if @register.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@register.errors.count, "error") %> prohibited this register from being saved:</h2>
<ul>
<% @register.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :date %><br />
<%= f.date_select :date %>
</div>
<div class="field">
<h4>Buyer</h4>
</div>
<div class="field">
<%# f.fields_for :buyers do |builder| %>
<%= render :partial => "buyer_fields", :locals => {:f => f } %>
<%# end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
_buyer_fields.html.erb
是
<% f.fields_for :buyers do |buyers_form| %>
<div class="fields">
<p>
<%= buyers_form.label :name, "Name" %><br/>
<%= buyers_form.text_field :name %>
</p>
<h4>Address</h4>
<% f.fields_for :addresses do |builder| %>
<%= render :partial => 'address_fields', :locals => { :f => builder} %>
<% end %>
</div>
<% end%>
而且_address_fields.html.erb
是
<p class="fields">
<table>
<tr>
<td>
<%= f.text_area :name, :rows => "2",:cols => "20" %>
</td>
</tr>
</table>
</p>
register
模型是
class Register < ActiveRecord::Base
attr_accessible :date, :book_ids,:buyers_attributes
has_many :authorships
has_many :books, :through => :authorships
has_many :buyers
#accepts_nested_attributes_for :buyers, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
accepts_nested_attributes_for :buyers, :allow_destroy => :true,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end
buyer
模型是
class Buyer < ActiveRecord::Base
belongs_to :register
attr_accessible :addresses_attributes, :name
has_many :addresses, :dependent => :destroy
accepts_nested_attributes_for :addresses, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
end
模型address
是
attr_accessible :name
belongs_to :buyer
但只显示注册表。如何在 ruby on rails 3.2.9 中以单一形式集成两个模型?请帮忙。