0

複数のモデルを 1 つのフォームに統合するタスクがありました。1 つのフォーム「登録」と 2 つのモデルbuyeraddress. しかし、これを行うことで、2 つのフォームを一緒に添付することはできません。
_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で2つのモデルを単一の形式で統合するにはどうすればよいですか? 助けてください。

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 に答える