Rails 3:使用belongs_to关联呈现的嵌套表单

时间:2011-08-09 14:59:27

标签: ruby-on-rails ruby-on-rails-3 nested-forms nested-attributes

我正在努力获得使用belongs_to关联呈现的嵌套表单。

我期待“_form.html.erb”(下面)中的地址字段被渲染得正确,但显然它不是,我只是无法绕过它来解释原因!

Rails版本:3.09

这是代码。

型号:

Store.rb

class Store < ActiveRecord::Base
  has_and_belongs_to_many :products
  belongs_to :store_address, :foreign_key => "address_id", :class_name => "Address"
  ......

end

地址没有对商店模型的任何引用(它是独立的)

控制器

stores_controller.rb

  def new
    @store = Store.new
    @store.build_store_address
    respond_with(@store)
  end

查看

new.html.erb

<% form_for(@store, :url => collection_url) do |f| %>
  <%= render :partial => "form", :locals => { :f => f } %>
  <p class="form-buttons">
    <%= button t('continue') %>

  </p>
<% end %>

_form.html.erb

<%=t(:store_name)%> : <%= text_field :store, :name %>
<%=t(:store_admin_email)%> : <%= text_field :store, :admin_email %>

<fieldset> 
    <legend><label><%=t(:address)%></label></legend> 
    <% f.fields_for :store_address do |address_form| %>
    <table> 
        <tbody><tr> 
            <td width="200"><label><%=t(:line_1)%></label></td><td> 
            <%= address_form.text_area :address1, :rows => 2%> 
            </td> 
        </tr> 
        <tr> 
            <td><label><%=t(:line_2)%></label></td><td> 
            <%= address_form.text_area :address2, :rows => 2 %>  
            </td> 
        </tr> 
        <tr> 
            <td><label><%=t(:city)%></label></td><td> 

            <%= address_form.text_field :city %> 

            </td> 
        </tr> 
.......

这会呈现商店名称。但地址方面没什么。请帮忙!

1 个答案:

答案 0 :(得分:3)

我认为您在&lt;%f.fields_for ... 错过了 = 。它应该是&lt;%= f.fields_for ...

过去经常发生这种情况,遗漏了这一件事,然后想知道为什么嵌套表格不会呈现。