Rails 4 - 使用嵌套形式的AJAX销毁子记录,但表单仍然提交此记录

时间:2014-12-27 04:16:06

标签: ruby-on-rails

我将配方和配料模型关联设为

模特协会

Recipe has_many :ingredients
accepts_nested_attributes_for :ingredients, :reject_if => :all_blank, :allow_destroy => true

Ingredient belongs_to :recipe

以嵌套的形式,我有一个用Ajax销毁成分记录的链接。

查看

<%= simple_form_for @recipe do |f| %>
    ...
    <%= f.simple_fields_for :ingredients do |i| %>
        <%= i.input_field :name %>
        <%= link_to "Delete", recipe_ingredient_path(@recipe, i.object), method: :delete, remote: true %>
    <% end %>
<% end %>

销毁嵌套资源可以很好地工作,但是这个嵌套表单提交仍然包含已销毁资源属性的参数会出现问题。 因此,通过表单更新,recipes_controller会抱怨要更新的记录已被销毁。

食谱控制器

...
def update
  if @recipe.update(recipe_params)
    respond_with(@recipe)
  else
    render 'edit'
  end
end
...

private
  def recipe_params
    params.require(:recipe).permit(:title, :image, :serving, :prep, :cook, :steps, ingredients_attributes: [:id, :name, :_destroy])
  end

成分控制器(仅具有销毁以处理Ajax响应)

def destroy
  @ingredient = Ingredient.destroy(params[:id])
  respond_to do |format|
    format.js
  end
end

以下是我得到的错误。 如果查看请求的参数,仍然会传递一种成分资源 即使所有成分在提交前都被妥善销毁。

我明白问题是什么,但我很难解决这个问题。

error message

0 个答案:

没有答案