Search code examples
ruby-on-railsapplicationcontroller

Render :layout is searching for partial instead of layout


I understand this is a bad idea, but from what I've seen in ApplicationControllers, using:

render :layout => "something" ...

Should render using a layout located at views/layouts/something.html.erb

However, when I am making this call from inside of a view, it errors out with:

Missing partial my_controller_name/something with ... 
Searched in:
* "{path here}/app/views"

Which seems to me its looking for a partial, instead of a layout as I specified. Does anyone know what is going on with that?

A sufficient example small enough to reproduce it:

<%= render :layout => 'something' do %>
  <div>Hello</div>
<% end %>

This is all under Rails vs 4.0.2


Solution

  • render works differently in controllers than it does in views. In controllers, it's primarily for rendering action templates, while in views, it's primarily for rendering partial templates. When you want to render a specific layout for an action, you have a few options, but all of them are in the controller.

    If you want every action in a particular controller to use that layout, you can either specify layout 'something' in that controller (usually near the top) or for a ApplesController, you can create a new layout in app/views/layouts/apples.html.erb and this will automatically be used as the default layout for the ApplesController.

    If you want just a single action in a controller to use that layout, you can use your render layout: 'something' inside of a controller action, where the action to render is implied to be the current action.

    Links from the Rails docs: