Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fields_for disappear when adding accepts_nested_attributes_for

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?!?!

like image 346
Acuña Avatar asked Aug 02 '12 00:08

Acuña


1 Answers

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

like image 152
house9 Avatar answered Sep 30 '22 10:09

house9