如何使用 Rails 中的现有数据预填充嵌套字段?

How to pre-populate nested fields with existing data in Rails?

我有收据模型,里面有很多成分。所以,我使用

gem "nested_form"
gem "cocoon"

用于嵌套表单。创建新成分(或几种成分)时一切顺利。但我想在编辑时用现有数据预先填充这些字段。

_form.html.slim

= f.fields_for :ingredients, [@receipt.ingredients.build] do |i|
    = render 'ingredient_fields', f: i
    = link_to_add_association 'Add ingredient', f, :ingredients, class: "btn btn-success"
  br/

_ingredient_fields.html.slim

.nested-fields
  .row
    .form-group.col-xs-5
      .field        
        = f.text_field :name, placeholder: "Name", class: "form-control"
    .form-group.col-xs-3
      .field
        = f.number_field :count, placeholder: "Count", class: "form-control"
    .form-group.col-xs-3    
      .field
        = f.select :count_name, [['gr', 'gr'], ['kg', 'kg']], placeholder: "count name", class: "form-control"
    = link_to_remove_association image_tag("/close.png"), f

这是收据控制器的一部分

def edit
    @ingredients = @receipt.ingredients
end

在你的表格中你应该写:

= f.fields_for :ingredients do |i|

这将遍历收据的现有成分。如果您仍然想在创建新收据时默认添加新成分,您可以按照以下最简单的方式在 receipts_controller:

def new
  @receipt = Receipt.new
  @receipt.ingredients.build
end