9

Robię zagnieżdżone formularza w Rails 3.2.5, ale po dodaniu accepts_nested_attributes_for mój fields_for zniknąć (po prostu przestać pokazywać w moim formularzu).
To są moje modele:Fields_for znikają podczas dodawania accepts_nested_attributes_for

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

    has_many :variants 
    accepts_nested_attributes_for :variants 

    validates :title, presence: true 
end 

Mój drugi model jest

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

I moim zdaniem mam

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

Część między ** jest tą, która nie jest drukowana. A kiedy usuwam accepts_nested_attributes_for w moim Modelu produktu fields_for zacząć wyświetlać ponownie, ale mój formularz nie będzie działać.
Co się dzieje?!?!

Odpowiedz

10

w kontrolerze nowego połączenia działań

@product.varients.build 

To powinno stworzyć 1 w varient pamięci w kolekcji varient produkt i powinno wiązać się z polami dla

+0

Thankyou! Nie wiedziałem, że fields_for potrzebował istniejącego atrybutu, aby renderować pola. –

+2

Jeśli było to stowarzyszenie 'has_one', musisz wywołać' @ product.build_varient'. Zajęło mi trochę czasu, aby to odkryć. Więcej informacji można znaleźć w [documentation] (http://guides.rubyonrails.org/association_basics.html#methods-added-by-has-one). –

Powiązane problemy