2009-07-14 143 views
17

我试图将一个网站分成两部分。一个应该使用应用程序布局,另一个应该使用管理布局。在我的application.rb中我创建了一个功能如下:Ruby on Rails - 渲染布局

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

并在控制器它可能是一个或另一个我把

before_filter :admin_layout 

也能正常工作一段网页(其中它只是文字),但对于其他人,我得到的经典错误:

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 

有没有人有我想念的想法?我应该如何正确使用渲染和布局?

回答

38

方法render将实际尝试呈现内容;当你想要做的就是设置布局时,你不应该调用它。

Rails有所有这一切在烘烤的图案简单地传递一个符号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

+1

如果logged_in?和current_user.is_able_to('siteadmin') current_user可能为零,如果没有登录! – 2009-07-15 06:57:36

5

也许你需要检查用户是否先登录?

def admin_layout 
    if current_user and current_user.is_able_to 'siteadmin' 
    render :layout => 'admin' 
    else 
    render :layout => 'application' 
    end 
end 
+0

.nil?在except语句是多余的,虽然 – Gav 2009-07-15 11:29:04

1

这可能是因为current_usernil,当用户没有登录时。可以测试.nil?或初始化对象。

0

尝试molf的回答:

if logged_in?和current_user.is_able_to(“siteadmin”)

0

当前用户在properbly设置用户之后登录。在这种情况下,你应该有一个选项,以确定是否要在

记录像

if [email protected]_user.nil? 
    if @current_user.is_able_to("###") 
    render :layout => "admin" 
    else 
    render :layout => "application" 
    end 
end 

然后它只会输入if语句,如果你的@current_user不是零。