RecordNotFound 在控制器中#edit

RecordNotFound in Controller#edit

我正在尝试在控制器中为嵌套资源创建编辑操作。当我尝试 运行 编辑操作时,我收到以下错误:

ActiveRecord::RecordNotFound in IngredientsController#edit
Couldn't find Recipe with 'id'=287

下面是我的控制器:

class IngredientsController < ApplicationController
  def edit
    @recipe = Recipe.find(params[:id])
    @ingredient = @recipe.ingredients.find(params[:id])
  end
end

还有我的 link 编辑:

%= link_to 'Edit Ingredient', edit_recipe_ingredient_path(@recipe, ingredient) %>

知道是什么原因造成的吗?如果需要任何其他代码来提供问题的上下文,请告诉我。谢谢!

尝试将 edit 操作更改为:

def edit
    @recipe = Recipe.find(params[:recipe_id])
    @ingredient = @recipe.ingredients.find(params[:id])
end

这似乎是与其他方法的唯一区别。另外,由于您在 IngredientsController 中,因此 params[:id] 是成分的 id,而不是食谱。

您似乎没有 Recipeid,这就是 Recipe.find(params[:id]) 引发错误的原因。否则它不会失败,但成分会以完全不同的配方结束。