【问题标题】:Rails ApplicationControllerRails 应用程序控制器
【发布时间】:2014-03-30 10:35:19
【问题描述】:

我正在关注 Rails 教程 (http://tutorials.jumpstartlab.com/projects/blogger.html#blogger-2),正在制作一个简单的博客。在其中一个练习中,它要求我为我的 Articles_Controller 实现 destroy 方法(articles 是博客文章结构的模型)。

我已经实现了delete功能,但是之后尝试redirect_to article_path(@article)时,找不到记录(当然是被删除了)。我想知道如何重定向到索引页面?

删除一篇文章后,我得到 rails 错误页面并且:

error: ActiveRecord::RecordNotFound in ArticlesController#show 

我的应用程序/控制器/articles_controller.rb:

def destroy
  @article = Article.find(params[:id])
  flash.notice = "Article '#{@article.title}' destroyed."
  redirect_to article_path(@article)
  @article.destroy
end

ArticleController#show中定义的方法

def show
  @article = Article.find(params[:id])
end 

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你可以重定向到索引路径 redirect_to articles_path

    所以:

    def destroy
      begin
        @article = Article.find(params[:id])
        if @article.destroy
          redirect_to articles_path, notice: "Article '#{@article.title}' destroyed."
        else
          redirect_to article_path(@article), alert: "Article could not be destroyed."
        end
      rescue ActiveRecord::RecordNotFound
        redirect_to articles_path, alert: "Article with id '#{params[:id]}' not found"
      end
    end
    

    【讨论】:

      【解决方案2】:

      如果您想重定向到应用程序的索引页面。你可以这样做。

      def destroy
         @article = Article.find(params[:id])
         @article.destroy
         flash.notice = "Article '#{@article.title}' destroyed"
         redirect_to root_index
      end
      

      【讨论】:

        猜你喜欢
        • 2012-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-02
        • 2011-06-01
        • 2018-08-13
        相关资源
        最近更新 更多