Ruby on Rails – 渲染布局
我正在尝试将网站分成两部分。 一个应该使用应用程序布局,另一个应该使用管理布局。 在我的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
有没有人知道我错过了什么? 我该如何正确使用渲染和布局?
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
详情请见此处 。
也许您需要先检查用户是否已登录?
def admin_layout if current_user and current_user.is_able_to 'siteadmin' render :layout => 'admin' else render :layout => 'application' end end
这可能是因为当用户未登录时current_user
为nil
。要么测试.nil?
或初始化对象。
尝试molf的回答:
如果logged_in? 和current_user.is_able_to(’siteadmin’)
您的当前用户在用户登录后正确设置。在这种情况下,您应该有一个选项来确定您是否已登录
喜欢
if !@current_user.nil? if @current_user.is_able_to("###") render :layout => "admin" else render :layout => "application" end end
然后,如果你的@current_user不是nil,它只会输入if语句。