Problems rendering a layout in Rails3

From time to time we like to share technical tips when we’ve uncovered a solution to a problem that might help other Rails developers.

Spiffy Stores is written using the Ruby on Rails framework, and we encountered a glitch with the Rails3 layouts. Basically we couldn’t get the layout to display, even though all the syntax was correct. Others have experienced this sort of problem. See http://stackoverflow.com/questions/6605716/cant-render-layout-in-rails-3 for an example.

After lots of digging around and tracing, the answer became clear. The AbstractController::Layouts module has an initialize method, but this method was not being called when a new controller was created.

If you experience this problem, then check any modules that you have included in your controller, as one of them has an initialize method that doesn’t call ‘super’.

If an included module needs an initialize method, then it needs to follow this pattern:

def initialize(*)
  # Module initialization code here
  super
end

If the call to ‘super’ isn’t included, then the initialization chain stops, and your controller won’t be properly initialized. You can find out all the included modules for a controller by executing this code from the console:

MyController.ancestors