Ruby on rails RubyonRails-渲染布局
我正试图将一个网站分成两个部分。一个应该使用应用程序布局,另一个应该使用管理布局。在my application.rb中,我创建了一个函数,如下所示:Ruby on rails RubyonRails-渲染布局,ruby-on-rails,layout,render,Ruby On Rails,Layout,Render,我正试图将一个网站分成两个部分。一个应该使用应用程序布局,另一个应该使用管理布局。在my application.rb中,我创建了一个函数,如下所示: def admin_layout if current_user.is_able_to('siteadmin') render :layout => 'admin' else render :layout => 'application' end end 在控制器中,它可能是我放置的一个或另一个 befo
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
有人知道我错过了什么吗?如何正确使用渲染和布局?也许您需要先检查用户是否已登录
def admin_layout
if current_user and current_user.is_able_to 'siteadmin'
render :layout => 'admin'
else
render :layout => 'application'
end
end
方法
render
将实际尝试呈现内容;当您只想设置布局时,不应该调用它
Rails有一个用于所有这些烘焙的模式。只需将一个符号传递给布局
,就会调用具有该名称的方法来确定当前布局:
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
class MyController 如果你登录了?和当前用户。是否可以('siteadmin')
“管理员”
其他的
“应用程序”
结束
结束
结束
.这可能是因为当用户未登录时,
当前用户
为nil
。测试.nil?
或初始化对象。尝试molf的答案:
如果你登录了?和当前用户。是否能够('siteadmin')在用户登录后,您的当前用户已在中正确设置。在这种情况下,您应该可以选择是否登录 像
如果@current\u用户不是nil,它将只输入if语句。如果登录?和当前用户。如果当前用户未登录,则可能为零!在该行之前,我还有其他检查要检查用户是否登录。这是惊人的,虽然,我甚至从来没有想过调用一个函数后布局。非常简单,非常有用。谢谢你。感谢那些正在检查这个的人。我本应该多做一点研究:第一条评论会回答我的问题。@molf你答案中的链接断了。nil?但是,除非语句是多余的
if !@current_user.nil?
if @current_user.is_able_to("###")
render :layout => "admin"
else
render :layout => "application"
end
end