Godzilla74 Godzilla74 - 5 months ago 13
Ruby Question

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?

Answer

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]