2016-11-30 60 views
0

我一直在寻找其他人关于这个问题的文章。不幸的是,一段时间后,我陷入了困境。我明白,一些控制器方法无法找到与相关'ID'相关的故事,并将其呈现给视图,因此我的错误。ActiveRecord :: RecordNotFound(找不到与'id'= =的故事):

但是,我不明白我如何编辑我的控制器方法/路由,因此它实际上可以找到'1,2,3,4等'的id。我相信它试图寻找与ID不同的东西。 “创建”和“显示”方法正在创建相同的错误。

错误在屏幕上:

ActiveRecord::RecordNotFound in StoriesController#create 

Couldn't find Story with 'id'= 

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

在这里,我已经把ID为故事PARAMS找到方法,但它没有找到它。为什么?

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 

我的routes.rb:

Rails.application.routes.draw do 

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

发布完整的错误,请 –

+0

你正在尝试找到带id的stroy,但没有在参数中传递id这是主要原因 –

+0

你说这是创建和显示?看起来只是从上面的错误创建,它是否也显示,如果是这样,你能给我一个你正在使用的路线的例子,它需要有一个ID,例如“/无论/ therouteis/1” –

回答

2

你想改变“:find_story”不包括创建因为这是告诉它寻找一个id,但没有当创建页面上,您要创建一个新的,没有找到一个存在

的before_action所以改变这种

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

您的故事问题是您尝试使用的路线。展会寻找一个ID,因为我上面提到的同样的理由,因此路由必须像

stories/show/1 

,其中“1”是你想要的故事的ID。

+0

这工作,谢谢!如果我继续/故事/显示,它给了我类似的错误'StoryController#show'中的ActiveRecord :: RecordNotFound''找不到故事'id'= show' – Benjamints

+0

需要成为“stories/show /:id”,所以“stories/show/1”例如 –

+0

你不会做'故事/展示',这不是一个RESTful路线。 'story/1'显示id为1的故事等... – SteveTurczyn

0

的ActiveRecord :: RecordNotFound在StoriesController#创建

你有before_action :find_story与创建方法,试图找到Story但没有:id params中

所以,你需要删除:createbefore_action列表中采取行动并将其更改为

before_action :find_story, only: [:destroy, :show, :edit, :update] 
相关问题