Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - render layout

I'm trying to split up a web site into two sections. One which should use the application layout and one that should use the admin layout. In my application.rb I created a function as follows:

def admin_layout
  if current_user.is_able_to('siteadmin')
    render :layout => 'admin'
  else
    render :layout => 'application'
  end
end

And in the controllers where it might be one or the other I put

before_filter :admin_layout

This works fine for some pages (where its just text) but for others I get the classic error:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each

Does anyone have an idea of what I'm missing? How should I properly use render and layout?

like image 913
RyanJM Avatar asked Jul 14 '09 21:07

RyanJM


People also ask

What is the layout in Ruby on Rails?

A layout defines the surroundings of an HTML page. It's the place to define a common look and feel of your final output. Layout files reside in app/views/layouts. The process involves defining a layout template and then letting the controller know that it exists and to use it.

How can you tell Rails to render without a layout?

2.2. By default, if you use the :plain option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option and use the . text. erb extension for the layout file.

What is render in Ruby on Rails?

Rendering is the ultimate goal of your Ruby on Rails application. You render a view, usually . html. erb files, which contain a mix of HMTL & Ruby code. A view is what the user sees.

How should you use nested layouts in Rails?

Nesting layouts is actually quite easy. It uses the content_for method to declare content for a particular named block, and then render the layout that you wish to use. So, that's the normal application layout.


1 Answers

The method render will actually attempt to render content; you should not call it when all you want to do is set the layout.

Rails has a pattern for all of this baked in. Simply pass a symbol to layout and the method with that name will be called in order to determine the current layout:

class MyController < ApplicationController
  layout :admin_layout

  private

  def admin_layout
    # Check if logged in, because current_user could be nil.
    if logged_in? and current_user.is_able_to('siteadmin')
      "admin"
    else
      "application"
    end
  end
end

See details here.

like image 153
molf Avatar answered Oct 05 '22 23:10

molf