我想一个网站分成两个部分。 其中一个应该使用应用程序布局和一个应该使用管理布局。 在我的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
实际上将试图呈现内容; 当你想要做的就是设置布局你不应该把它。
轨道具有用于所有这一切在烘烤的图案简单地传递一个符号。 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')
您当前的用户在properbly设置在用户登录后,在这种情况下,你应该有一个选项,以确定您是否已经登录
喜欢
if !@current_user.nil?
if @current_user.is_able_to("###")
render :layout => "admin"
else
render :layout => "application"
end
end
然后,它会只如果你的@current_user中不无进入if语句。