如何从轨道上的ruby中的另一个模型中获取一个模型值?

时间:2012-11-19 08:33:28

标签: ruby ruby-on-rails-3.2

我有一个任务是在一个表单中集成多个模型。我有一个表单'register'和两个模型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

但只显示注册表单。如何在轨道3.2.9上的红宝石中以单一形式集成两个模型?请帮忙。

1 个答案:

答案 0 :(得分: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 %>