2009-07-14 141 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不是零。