Last Updated: February 25, 2016
·
3.006K
· vitorbal

Using a before_filter to change the template that a controller action will render

If you ever need to change the template that a controller action will render depending on some conditions, you can do this using a before_filter and some rails magic.

For example, for a project I'm working on at work, we wanted that every action should render its view without the layout if the request received was an AJAX request. Here is how I did it:

class ApplicationController < ActionController::Base
    before_filter :handle_xhr_layout

    layout :layout_by_resource

    # If the request is an xhr, we don't render any layout
    def handle_xhr_layout
        if request and request.xhr?
            self.class.layout nil
        end
    end
end

Stateless Controllers

One thing to notice is that we do not need to set self.class.layout back to our default layout. This is because in MVC, a controller is stateless for each request, so Rails creates an instance of the controller for every request. (As seen on the Rails guides).