0

我的任务是将多个模型集成到一个表单中。我有一个表单“注册”和两个模型buyeraddress。但是通过这样做,我不能将两个表格附加在一起。
_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 中以单一形式集成两个模型?请帮忙。

4

1 回答 1

0

您的嵌套地址视图是错误的。进行一些更改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>

  <%= buyers_form.fields_for :addresses do |builder| %>
     <%= render :partial => 'address_fields', :locals => { :f => builder} %>   
  <% end %>

</div>
<% end %>
于 2012-11-19T09:37:10.067 回答