【问题标题】:ActiveRecord::RecordNotFound in ArticlesController#show Couldn't find Article with 'id'ActiveRecord::RecordNotFound in ArticlesController#show 找不到带有“id”的文章
【发布时间】:2014-07-25 21:29:32
【问题描述】:

我正在从 Jumpstart 实验室 http://tutorials.jumpstartlab.com/projects/blogger.html 做关于创建博客应用程序的教程

当我删除文章时,我遇到了错误“ActiveRecord::RecordNotFound in ArticlesController#show Couldn't find Article with 'id”

错误发生在 artciles_controller.rb 的第 10 行,即 @article = Article.find(params[:id])

 articles_controller.rb

class ArticlesController < ApplicationController
    include ArticlesHelper



   def index
       @articles = Article.all
   end
   def edit
     @article = Article.find(params[:id])
   end
   def show
       @article = Article.find(params[:id])
       @comment = Comment.new
       @comment.article_id = @article.id
   end
   def new
       @article = Article.new
   end
   def create
     @article = Article.new(article_params)
     @article.save
     redirect_to article_path(@article)
   end
   def destroy
       @article = Article.find(params[:id])
       @article.destroy
       redirect_to article_path(@article)
   end
   def update
       @article = Article.find(params[:id])
       @article.update(article_params)
       flash.notice = "Article '#{@article.title}' Updated!"
       redirect_to article_path(@article)
   end
end

show.html.erb

<h1><%= @article.title %></h1>
<p><%= @article.body %></p>
<h3>Comments (<%= @article.comments.size %>)</h3>
<%= render partial: 'arti`enter code here`cles/comment', collection: @article.comments %>
<%= link_to "edit", edit_article_path(@article) %>
<%= render partial: 'comments/form' %>
<%= link_to "<< Back to Articles List", articles_path %>
<%= link_to "delete", article_path(@article) , 
        method: :delete , 
     data: {confirm: "Really delete the article?"}%>

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord


    【解决方案1】:
    def destroy
        @article = Article.find(params[:id])
        @article.destroy
       redirect_to article_path(@article)
    end
    

    如果您在此处遵循此代码的逻辑,则您正在销毁文章,然后重定向到您刚刚销毁的文章。重定向工作正常,但是因为您刚刚销毁了它不存在的文章,所以show 找不到 ID。您需要重定向到其他内容(例如文章索引)。

    所以替换

    redirect_to article_path(@article)
    

    任何其他有效的重定向(此示例将重定向到文章索引)

    redirect_to articles_path
    

    【讨论】:

    • 谢谢。我重定向到了articles_path,现在可以正常工作了
    【解决方案2】:

    错误是您正在重定向到 article_path(文章详细信息)但该对象在上一行中被破坏,解决方案是重定向到文章列表,实际上是索引方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      相关资源
      最近更新 更多