[英]How to “inherit” a class variable from ApplicationController
I'm a little new to rails. 我是Rails的新手。
Say I want to do something like: 假设我想执行以下操作:
def is_admin?
@admin = User.grab(session[:username]).admin
end
I can define this in the ApplicationController but then I have to call is_admin?()
in every method in every subsequent controller. 我可以在ApplicationController中定义它,但随后必须在每个后续控制器中的每个方法中调用
is_admin?()
。 Is there a way around this that I am not aware of? 有没有办法解决我不知道的问题?
Use a :before_filter
at the start of each controller: 在每个控制器的开始处使用
:before_filter
:
before_filter :is_admin
At least then you don't have to do it for every method. 至少您不必为每种方法都这样做。
I'm not sure exactly what the problem with calling is_admin?
我不确定调用
is_admin?
到底出了什么问题is_admin?
is. 是。 Calling methods in Ruby is pretty cheap.
Ruby中的调用方法非常便宜。 You may want to "memoize" the return value to avoid calling to the database every time the method is called:
您可能需要“记住”返回值,以避免每次调用该方法时都调用数据库:
def is_admin?
unless defined?(@is_admin)
@is_admin = User.grab(session[:username]).admin
end
@is_admin
end
Since is_admin?
由于
is_admin?
can return a falsey value, ||=
won't work. 可以返回假值,
||=
将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.