【发布时间】:2016-12-17 20:03:54
【问题描述】:
一个食谱有很多成分和方向,每个都属于一个食谱。我的views/new.html.haml 呈现一个_form 部分,它呈现嵌套的部分。它在提交时拒绝说所需的嵌套元素不存在。我不确定我做错了什么或错过了什么。我已经反复查看了代码和茧文档。任何帮助将不胜感激。
models/recipe.rb
has_many :ingredients
has_many :directions
accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :directions, reject_if: :all_blank, allow_destroy: true
在 _form.html.haml partial 中使用 simple_form gem
%h3 Ingredients
#ingredients
= f.simple_fields_for :ingredients do |ingredient|
= render 'ingredient_fields', f: ingredient
.links
= link_to_add_association 'Add Ingredient', f, :ingredients
%h3 Directions
#directions
= f.simple_fields_for :directions do |direction|
= render 'direction_fields', f: direction
.links
= link_to_add_association 'Add Step', f, :directions
= f.button :submit
这链接到每个嵌套元素、成分和方向的部分...
views/recipes/_direction_fields.html.haml
.nested-fields
= f.input :step, input_html: { class: 'form-input form-control' }
= link_to_remove_association "Remove Step", f, class: 'btn btn-default form-button'
views/recipes/_ingredient_fields.html.haml
.nested-fields
= f.input :name, input_html: { class: "form-input form-control" }
= link_to_remove_association "Remove", f, class: "form-button btn btn-default"
当我尝试提交包含说明和成分的新食谱时,我会收到回滚通知,并在阅读...
2 阻止保存此配方
必须存在成分配方 必须存在方向配方
【问题讨论】:
-
我猜你在
Ingredient和Direction中验证了配方必须存在,例如validates_presence_of :recipe。你如何保存?我认为如果您检查:recipe_id的存在,它可能会起作用(因为通常它们都保存在一起)。 -
即使我把所有的验证都拿出来也不起作用。
标签: ruby-on-rails nested-forms model-associations cocoon-gem