问题描述
在其中一个控制器中,我需要特定的布局.我在开始处添加了layout
.效果很好.
In one of the controller, I need a specific layout. I added layout
at the beginning. It works well.
但是如果我为一些基于控制器的变量添加initialize
函数. Rails似乎只是忽略了layout
命令.
But if I add an initialize
function for some controller-based variable. Rails seems just ignore the layout
command.
有人有同样的问题吗?我该如何解决?
Is anyone have same problem? How can I fix it?
class AdminsController < ApplicationController
layout "layout_admins"
def initialize
@Title = "Admins"
end
def index
....... some code here
end
end
推荐答案
initialize
在Rails内部使用,以便初始化控制器的新实例,以便随后可以在其上提供请求.通过以这种特定方式定义此方法,您正在破坏Rails .
initialize
is used internally to Rails to, well, initialize a new instance of your controller so it can then serve requests on it. By defining this method in this particular manner, you are breaking Rails.
有一条路要走!隧道尽头的灯.彩虹尽头的一罐金:
There is a way through! A light at the end of the tunnel. A pot of gold at the end of the rainbow:
def initialize
@title = "Admins"
super
end
看到那边的super
小电话吗?这将调用超类的initialize
方法,完全执行Rails否则会执行的操作.现在,我们已经介绍了如何 方式进行操作,下面我们来介绍如何实现官方认可的" Rails方式
See that little super
call there? That'll call the superclass's initialize
method, doing exactly what Rails would do otherwise. Now that we've covered how to do it your way, let's cover how to do it the "officially sanctioned" Rails way:
class AdminsController < ApplicationController
before_filter :set_title
# your actions go here
private
def set_title
@title = "Title"
end
end
是的,这是更多的代码,但是它会减少凝视您的代码的其他人的挫败感.这是常规的操作方式,我强烈建议您遵循以下约定,而不是魔术".
Yes, it's a little more code but it'll result in less frustration by others who gaze upon your code. This is the conventional way of doing it and I strongly encourage following conventions rather than doing "magic".
如果您使用的是Rails 5,则需要使用before_action
而不是before_filter
.
If you're using Rails 5 then you'll need to use before_action
instead of before_filter
.
这篇关于初始化会中断rails中的布局设置吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!