ruby-on-railsrubycontrollernested-resources

RecordNotFound in Controller#edit


I am attempting to create an edit action in a controller for a nested resource. When I attempt to run the Edit action, I receive the following Error:

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

Below is my controller:

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

And my link to the Edit:

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

Any ideas what may be causing this? Please let me know if any other code is needed to give context to the problem. Thank You!


Solution

  • Try changing the edit action to:

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

    It seems to be the only difference with the rest of the methods. Plus, since you are in the IngredientsController the params[:id] is the id of the Ingredient, not of the Recipe.

    You don't seem to have a Recipe with that id, that's why Recipe.find(params[:id]) throws an error. Otherwise it wouldn't fail but the ingredient would end up in a totally different recipe.