Godzilla74 Godzilla74 - 1 year ago 87
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


In the controller related to my
page, actually in
I'm loading

@company = current_user.company

@locations = if @company

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
) my
variable is no longer found.

Sure, I could add it to the
method in my
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 Source

You can create a method in your application_controller

def set_locations

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] 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download