Last Updated: February 25, 2016
·
1.159K
· bryanmikaelian

Rails Layouts and Inheritance

Once again, DHH's point of "Rails just being Ruby" holds true when it comes to layouts in Rails. I recently fixed a bug with our app where certain API end points were trying to render our application layout in JSON. This was causing some nasty errors. Why were our API controllers, that do not have any layouts associated with them, trying to render a layout?

Here is a brief example showing the situation:

class ApplicationController < ActionController::Base
    layout 'application'
end

class API::SomeController < ApplicationController
end

Notice anything? There is a "gotcha" here. The API controller will try to render the layout 'application'. Why? Since the API controller inherits from Application Controller, the layout specified at the application controller level will try be set on each of the API Controller actions due to inheritance. Quirky but it makes sense. The solution was to just kill any layout setting at the application controller level and keep at the individual controller level.

Lesson learned: be careful what you set at the application controller level.