Ruby on Rails的 - 呈现布局(Ruby on Rails - render layou

2019-06-25 23:22发布

我想一个网站分成两个部分。 其中一个应该使用应用程序布局和一个应该使用管理布局。 在我的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

有没有人有我失去了我的想法? 我应该如何正确使用渲染和布局?

Answer 1:

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

查看详情这里 。



Answer 2:

也许你需要检查用户在第一次签署?

def admin_layout
  if current_user and current_user.is_able_to 'siteadmin'
    render :layout => 'admin'
  else
    render :layout => 'application'
  end
end


Answer 3:

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



Answer 4:

尝试MOLF的回答有:

如果LOGGED_IN? 和current_user.is_able_to( 'siteadmin')



Answer 5:

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

喜欢

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

然后,它会只如果你的@current_user中不无进入if语句。



文章来源: Ruby on Rails - render layout