添加accepts_nested_attributes_for时,fields_for消失 [英] Fields_for disappear when adding accepts_nested_attributes_for

查看:78
本文介绍了添加accepts_nested_attributes_for时,fields_for消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Rails 3.2.5中做一个嵌套表单,但是当我添加accepts_nested_attributes_for时,我的fields_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  

我的第二个模特是

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

在我看来,我有

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

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

**之间的部分是未打印的部分.当我在产品模型字段中删除accepts_nested_attributes_for时,for_再次开始显示,但我的表单无法使用.
是怎么回事?!?!

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

推荐答案

在控制器中进行新操作调用

In the controller new action call

@product.varients.build

那应该在product varient集合中的内存变量中创建1,并且应该绑定到字段

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

这篇关于添加accepts_nested_attributes_for时,fields_for消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆