简体   繁体   中英

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.

If I had this situation where I had this code in my 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:

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?

Thanks!

Try setting your instance variable using a before_filter in your ApplicationController :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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