简体   繁体   English

如何在Rails中使实例变量可用于application.html.erb文件?

[英]How do you make an instance variable available to the application.html.erb file in Rails?

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应用程序的所有视图中使用某个方法中的实例变量,而我想知道这样做的“导轨”方法是什么。

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 ? 我该怎么做才能将该实例变量提供给我的application.html.erb I tried doing this but it doesn't work: 我尝试这样做,但是不起作用:

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. @subscriptions实例变量为nil,我不太清楚为什么。 What is the best way to do this in Rails? 在Rails中执行此操作的最佳方法是什么?

Thanks! 谢谢!

Try setting your instance variable using a before_filter in your ApplicationController : 尝试在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM