Rails render and return in before_action, DoubleRenderError

brodney picture brodney · Aug 20, 2014 · Viewed 10.1k times · Source

In a controller action with a before_action, using render something and return does not actually cause the controller to stop executing the rest of the action. In my testing, only when called in the controller action does and return work as I would expect.

# DoubleRenderError
class SomeController < ApplicationController
    before_filter :double_render, only: [:index]

    def index
        render file: "public/500.html", status: :internal_server_error
    end

    def double_render
        render file: "public/404.html", status: :not_found and return
    end
end

# Renders 404 only, no error
class SomeController < ApplicationController
    def index
        render file: "public/404.html", status: :not_found and return
        render file: "public/500.html", status: :internal_server_error
    end
end

What's going on here? Can before_actions stop the rest of a controller's execution?

Answer

Victor picture Victor · Aug 20, 2014

If your intention is to render the 404 page, you shouldn't render it manually in the before_filter. The right way of doing that is raising a routing error, like this:

raise ActionController::RoutingError.new('Not Found')

You could implement a method called "render_404", raise this exception in it and let the routing system do the rest.

EDIT: Actually, your code should work. I really don't know what is going on. I wrote the same thing here and it worked - the action method is never called if the before_filter renders something. What version of Rails are you using?