我正在尝试将网站分为两个部分。一种应使用应用程序布局,另一种应使用管理员布局。在我的application.rb中,我创建了一个函数,如下所示:
def admin_layout
if current_user.is_able_to('siteadmin')
render :layout => 'admin'
else
render :layout => 'application'
end
end
在 Controller 中可能放置一个或另一个
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
See details here。
关于ruby-on-rails - Ruby on Rails-渲染布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1128080/