11

I'm doing a nested form in Rails 3.2.5, but when I add the accepts_nested_attributes_for my fields_for disappear (they just stop showing in my form).
This are my models:

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

    has_many :variants
    accepts_nested_attributes_for :variants

    validates :title, presence: true
end  

My second model is

class Variant < ActiveRecord::Base
    belongs_to :product
    attr_accessible :price, :sku, :weight, :inventory_quantity, :product_id
end

And in my view I have

<%= 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 %>

_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>  

The part between the ** is the one that is not being printed. And when I remove accepts_nested_attributes_for in my Product model fields_for start showing again but my form won't work.
What's happening?!?!

Acuña
  • 295
  • 2
  • 8

1 Answers1

17

In the controller new action call

@product.varients.build

That should create 1 in memory varient in the product varient collection and it should bind to the fields for

house9
  • 19,614
  • 8
  • 52
  • 60
  • Thankyou! I didn't know that fields_for needed an existing attribute in order to render the fields. – Acuña Aug 02 '12 at 23:43
  • 4
    If it was an `has_one` association you'd need to call `@product.build_varient`. It took a while to me to find it out. See [documentation](http://guides.rubyonrails.org/association_basics.html#methods-added-by-has-one) for more info. – a.barbieri Jul 19 '16 at 16:34