【问题标题】:Fields_for disappear when adding accepts_nested_attributes_for添加 Accepts_nested_attributes_for 时,Fields_for 消失
【发布时间】:2012-08-02 00:50:21
【问题描述】:

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

** 之间的部分是没有被打印的部分。当我在我的产品模型 fields_for 中删除 accept_nested_attributes_for 时再次开始显示,但我的表单将无法正常工作。
发生了什么?!?!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 nested-attributes fields-for


    【解决方案1】:

    在控制器中调用新动作

    @product.varients.build
    

    这应该在产品变量集合的内存变量中创建 1,并且它应该绑定到字段

    【讨论】:

    • 谢谢!我不知道 fields_for 需要一个现有属性才能呈现字段。
    • 如果是has_one 关联,您需要致电@product.build_varient。我花了一段时间才找到它。请参阅documentation 了解更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多