我有Receipt模型,它有很多成分。所以,我用
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
答案 0 :(得分:2)
在你的表格中你应该写:
= f.fields_for :ingredients do |i|
这将迭代收据的现有成分。如果您仍然希望在创建新收据时默认添加新成分,则可以在receipts_controller
中执行以下最简单的操作:
def new
@receipt = Receipt.new
@receipt.ingredients.build
end