Sheryl
Sheryl

Reputation: 25

Why am I getting "AbstractController::DoubleRenderError" when calling redirect_to in after_action?

In the comments controller, I am redirecting to the articles show page after both create and destroy. So I decided to write an after_action which would do the 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

But this gives me AbstractController::DoubleRenderError after both create and destroy.

Why am I getting this error?

Upvotes: 1

Views: 1139

Answers (2)

Mike Vallano
Mike Vallano

Reputation: 326

By default, Rails will render views that correspond to the controller action. See Rails Guides.

So in your create and destroy actions, Rails is performing a render by default. Then your after_action (which happens after the action) is redirecting, so it's double rendering.

Instead of an after_action, you could call the goto_articles_page method in your controller actions.

For example:

  def destroy
    @comment.destroy
    goto_articles_page
  end

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

Upvotes: 2

fool-dev
fool-dev

Reputation: 7777

I think using return when rendering any action but when redirect_to use then not need to use return then finally you can remove and return

Rails guide very nicely explained that you can follow this carefully

redirect_to explanation

Hope to help

Upvotes: 0

Related Questions