19

我正在尝试将网站分成两个部分。一种应该使用应用程序布局,另一种应该使用管理布局。在我的 application.rb 中,我创建了一个函数,如下所示:

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

有人知道我缺少什么吗?我应该如何正确使用渲染和布局?

4

5 回答 5

41

该方法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

在此处查看详细信息

于 2009-07-14T21:22:44.720 回答
5

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

def admin_layout
  if current_user and current_user.is_able_to 'siteadmin'
    render :layout => 'admin'
  else
    render :layout => 'application'
  end
end
于 2009-07-14T21:19:05.147 回答
1

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

于 2009-07-14T21:25:18.020 回答
0

尝试 molf 的回答:

如果已登录?和 current_user.is_able_to('siteadmin')

于 2009-07-15T05:41:27.430 回答
0

在用户登录后,您的当前用户已正确设置。在这种情况下,您应该有一个选项来确定您是否已登录

 if !@current_user.nil?
   if @current_user.is_able_to("###")
     render :layout => "admin"
   else
    render :layout => "application"
   end
 end

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

于 2009-07-15T15:12:52.610 回答