[英]How do you make an instance variable available to the application.html.erb file in Rails?
我遇到一种情况,我想在Rails应用程序的所有视图中使用某个方法中的实例变量,而我想知道这样做的“导轨”方法是什么。
如果遇到这种情况,我的subscriptions_controller.rb
有以下代码:
def index
@subscriptions = current_user.subscriptions
end
我该怎么做才能将该实例变量提供给我的application.html.erb
? 我尝试这样做,但是不起作用:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def index
@subscriptions = current_user.subscriptions
end
end
@subscriptions
实例变量为nil,我不太清楚为什么。 在Rails中执行此操作的最佳方法是什么?
谢谢!
尝试在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.