9
我在Rails 3.2.5中做了一个嵌套窗体,但是当我添加accepts_nested_attributes_for
时,我的fields_for
消失了(它们只是停止在我的窗体中显示)。
这是我的模型:Fields_for在添加时消失accep_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
我的第二个模式是
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
<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>
**之间的部分是未打印的部分。当我在我的产品模型字段中移除accep_nested_attributes_for_for开始再次显示,但我的表单不起作用。
发生了什么?!?!
三江源!我不知道fields_for需要现有属性才能渲染字段。 – 2012-08-02 23:43:27
如果是'has_one'关联,则需要调用'@ product.build_varient'。我花了一段时间才找到它。有关更多信息,请参阅[documentation](http://guides.rubyonrails.org/association_basics.html#methods-added-by-has-one)。 – 2016-07-19 16:34:28