添加accepts_nested_attributes_for时,Fields_for消失

Acu*_*uña 11 ruby-on-rails nested-attributes fields-for ruby-on-rails-3 ruby-on-rails-3.2

我在Rails 3.2.5中做了一个嵌套的表单,但是当我添加accepts_nested_attributes_for我的fields_for消失时(他们只是停止在我的表单中显示).
这是我的模特:

class Product < ActiveRecord::Base
    attr_accessible :title, :description, :variants_attributes

    has_many :variants
    accepts_nested_attributes_for :variants

    validates :title, presence: true
end  
Run Code Online (Sandbox Code Playgroud)

我的第二个模特是

class Variant < ActiveRecord::Base
    belongs_to :product
    attr_accessible :price, :sku, :weight, :inventory_quantity, :product_id
end
Run Code Online (Sandbox Code Playgroud)

在我看来,我有

<%= form_for [:admin, @product], :html => {:multipart => true} do |f| %>

 <%= render 'admin/shared/error_messages', object: f.object %>

 <fieldset>
  <legend>Producto Nuevo</legend>  
    <div class="control-group">
      <%= f.label :title, 'Título', class: 'control-label' %>
      <div class="controls">
        <%= f.text_field :title %>
      </div>
   </div>

    **<%= f.fields_for :variants do |variant| %>
     <%= render 'inventory_fields', f: variant %>
    <% end %>**  

  <div class="actions">
    <%= f.submit 'Guardar', class: 'btn btn-primary' %>
  </div>
<% end %>
Run Code Online (Sandbox Code Playgroud)

_inventory_fields.html.erb

<div class="control-group">
  <%= f.label :inventory_quantity, 'How many are in stock?', class: 'control-label' %>
  <div class="controls">
    <%= f.text_field :inventory_quantity, class: 'span1', value: '1' %>
  </div>
</div>  
Run Code Online (Sandbox Code Playgroud)

**之间的部分是未打印的部分.当我在我的产品模型fields_中删除accepts_nested_attributes_for时,再次开始显示,但我的表单不起作用.
发生了什么?!?!

hou*_*se9 15

在控制器新动作调用中

@product.varients.build
Run Code Online (Sandbox Code Playgroud)

这应该在产品varient集合中创建1 in memory varient,它应该绑定到的字段

  • 如果它是一个`has_one`关联,你需要调用`@ product.build_varient`.我花了一段时间才找到它.有关详细信息,请参阅[documentation](http://guides.rubyonrails.org/association_basics.html#methods-added-by-has-one). (4认同)