Godzilla74
Godzilla74

Reputation: 2502

Rails where do global variables go?

I'm learning alot about the DRY concept in Rails so here's my question:

I have a fixed sidebar in my application that always needs to load various Objects, such as Locations.

In the controller related to my index page, actually in controllers/pages_controller.rb I'm loading @locations:

@company = current_user.company

@locations = if @company
   current_user.company.locations.order(:name)
else
   []
end

Which works fine for my navigation menu (sidebar), however, once I select a location and load a view delegated from a different controller (in this case locations/show.html.erb) my @locations variable is no longer found.

Sure, I could add it to the show method in my locations_controller.rb file, but that isn't very DRY considering I'd have to put the above code in every single controller method that relies on the sidebar navigation menu (all of them!) since it's fixed.

What's the DRY way to do this once and not have to do it in every controller?

Upvotes: 1

Views: 80

Answers (2)

Sharjeel
Sharjeel

Reputation: 15798

You can create a method in your application_controller

def set_locations
....
end

Then in your pages_controller and locations_controller add a before_filter

before_filter :set_locations

It will set call set location before all all methods of the pages and locations controller.

If you want to set locations only for few controller actions then call:

before_filter :set_locations,:only=>[:show,:index, :your_action_name] 

Updated:

In Rails 5 before_filter is deprecated and you can use before_action

Upvotes: 1

neydroid
neydroid

Reputation: 1951

You could add it to the ApplicationController in a method that runs before every action, every controller inherits from this ApplicationController so it will be available.

Upvotes: 0

Related Questions