I have a situation where I want to use an instance variable from a method in all views in a Rails application and I was wondering what is the 'Rails' way to do this.
我有这样一种情况,我想在Rails应用程序的所有视图中使用来自方法的实例变量,我想知道实现这一点的“Rails”方法是什么。
If I had this situation where I had this code in my subscriptions_controller.rb
:
如果我有这样的情况我的subscriptions_controller.rb中有这段代码:
def index
@subscriptions = current_user.subscriptions
end
What would I do to make this instance variable available to my application.html.erb
? I tried doing this but it doesn't work:
要让这个实例变量对我的application.html.erb可用,我该怎么做呢?我试过这么做,但没用:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def index
@subscriptions = current_user.subscriptions
end
end
The @subscriptions
instance variable is nil, and I'm not too sure why. What is the best way to do this in Rails?
@订阅实例变量为nil,我不太确定原因。在Rails中,最好的方法是什么?
Thanks!
谢谢!
1 个解决方案
#1
5
Try setting your instance variable using a before_filter
in your ApplicationController
:
尝试在应用程序控制器中使用before_filter设置实例变量:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_filter :set_subscriptions
def set_subscriptions
return if current_user.nil?
@subscriptions ||= current_user.subscriptions
end
end
#1
5
Try setting your instance variable using a before_filter
in your ApplicationController
:
尝试在应用程序控制器中使用before_filter设置实例变量:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_filter :set_subscriptions
def set_subscriptions
return if current_user.nil?
@subscriptions ||= current_user.subscriptions
end
end