Rails嵌套表单带有Cocoon gem,拒绝关联

时间:2016-12-17 20:03:55

标签: ruby-on-rails nested-forms model-associations cocoon-gem

食谱有许多成分和方向,每个都属于食谱。我的views/new.html.haml呈现_form部分,呈现嵌套的部分。它在提交时拒绝说明所需的嵌套元素不存在。我不确定我做错了什么或错过了什么。我已经多次查看了代码和cocoon文档。任何帮助将不胜感激。

模型/ 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部分

中使用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

这链接到每个嵌套元素,成分和方向的部分内容......

的观点/食谱/ _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'

的观点/食谱/ _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通过保存

防止此配方      

配料配方必须存在方向配方必须存在

1 个答案:

答案 0 :(得分:1)

这解决了我的问题。 cocoon gem attributes not saving when creating new recipe

Rails 5现在要求您在模型关联中声明inverse_of