为什么我会得到" AbstractController :: DoubleRenderError"在after_action中调用redirect_to时?

时间:2017-12-30 13:11:17

标签: ruby-on-rails

在评论控制器中,我在创建和销毁之后重定向到文章显示页面。 所以我决定写一个after_action来做redirect_to

class CommentsController < ApplicationController
  before_action :find_article
  before_action :find_comment, only: [:destroy]

  after_action :goto_articles_page, only: [:create, :destroy]

  def create
    @comment = @article.comments.create(comment_params)
  end

  def destroy
    @comment.destroy
  end

  private

    def comment_params
      params.require(:comment).permit(:commenter, :body)
    end

    def find_article
      @article = Article.find(params[:article_id])
    end

    def find_comment
       @comment = @article.comments.find(params[:id])
    end

    def goto_articles_page
      redirect_to article_path(@article) and return
    end
end

但是在创建和销毁之后,这给了我AbstractController::DoubleRenderError

为什么我收到此错误?

2 个答案:

答案 0 :(得分:1)

默认情况下,Rails将呈现与控制器操作对应的视图。 See Rails Guides.

因此,在您的createdestroy操作中,Rails默认执行渲染。然后,您的after_action(在操作后发生)正在重定向,因此它会进行双重渲染。

您可以在控制器操作中调用after_action方法,而不是goto_articles_page

例如:

  def destroy
    @comment.destroy
    goto_articles_page
  end

  def goto_articles_page
    redirect_to article_path(@article) #return not needed
  end

答案 1 :(得分:0)

我认为在return任何操作时使用rendering,但redirect_to使用return时不需要使用and return,最后您可以删除SELECT id AS p_id, name AS p_name, number_of_items AS items FROM ( SELECT product_id AS id FROM product_days WHERE available > 0 AND days_id BETWEEN 5 AND 10 GROUP BY 1 HAVING count(*) > 5 ) d JOIN product p USING (id);

Rails guide非常好地解释了你可以仔细阅读

redirect_to解释

希望能提供帮助