Reputation: 1489
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!
Upvotes: 2
Views: 1133
Reputation: 11628
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
Upvotes: 5