Benjamints Benjamints - 10 days ago 8
Ruby Question

ActiveRecord::RecordNotFound (Couldn't find Story with 'id'=):

I have been looking at other people's posts about this question. Unfortunately, still a while later I am stuck on it. I understand that a couple of the controller methods cannot find a story with the relevant 'ID' and render that to the views, hence my error.

However, I don't understand how I can edit my controller methods/routing so it can actually find the id of '1,2,3,4 etc'. I believe it is trying to look for a different from of ID. The 'create' and 'show' methods are creating the same error.

Error on screen:

ActiveRecord::RecordNotFound in StoriesController#create

Couldn't find Story with 'id'=

def find_story
@story = Story.find(params[:id])
end


Here, I have put in ID as the params for the story find method but it isn't finding it. Why?

class StoriesController < ApplicationController
before_action :find_story, only: [:destroy, :create, :show, :edit, :update]


def index
@stories = Story.order('created_at DESC')
end

def new
@story = Story.new
end

def create
@story = Story.new(story_params)
if @story.save
flash[:success] = "Your beautiful story has been added!"
redirect_to root_path
else
render 'new'
end
end

def edit
end

def update
if @story.update.attributes(story_params)
flash[:success] = "More knowledge, more wisdom"
redirect_to root_path
else
render 'edit'
end
end

def destroy
if @story.destroy
flash[:success] = "I think you should have more confidence in your storytelling"
else
flash[:error] = "Can't delete this story, sorry"
end
end

def show
@stories = Story.all
end

private

def story_params
params.require(:story).permit(:name, :description)
end

def find_story
@story = Story.find(params[:id])
end


end


My routes.rb:

Rails.application.routes.draw do

get 'stories/new/:id' => 'posts#show'
resources :stories
devise_for :users
root to: 'stories#index'
end

Answer

You want to change the ":find_story" to not include the create as that is what is telling it to look for an id, but there is no id when on the create page, you are creating a new one, not finding one that exists

so change the before_action to this

before_action :find_story, only: [:destroy, :show, :edit, :update]

Your issue with stories is the route you are trying to use. Show looks for an id, for the same reason I mentioned above, so the route need to be something like

stories/show/1

where "1" is the id of the story you want.