Rails 中的全局变量 [英] Global variable in Rails
本文介绍了Rails 中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 Rails 应用程序中有一个反馈表.反馈表单需要初始化@support 变量,并且它应该在每个页面上都可见.初始化很短:
I have a feedback form in my Rails application. The feedback form requires initializing of the @support variable, and it should be visible on every page. The initialization is very short:
@support = Support.new(:id => 1)
但是,最好将此变量初始化一次并从任何地方访问它.这怎么可能?
However it would be nice to have this variable initialized once and access it from everywhere. How is that possible to do?
推荐答案
您可以使用辅助方法(在应用程序控制器中)来初始化支持变量.像这样:
you can use a helper method (in the application controller) to initialize the support variable . Something like this :
class ApplicationController < ..
...
helper_method :my_var
def my_var
@support = Support.new(:id => 1)
end
...
end
这篇关于Rails 中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文