How do you define a function for partial in a controller to work in all views? Ruby on Rails

advertisements

For example, I'm placing the partial <%= render "layouts/location" %> in views all over the site. I need a controller for the layout (I tried layouts_controller.rb ) so I could do

def _location
    @city = request.location.city
    @state = request.location.state
  end

The partial contains the code <%= @city %>, <%= @state %>

This is all effectively, supposed to display the city and state of the visitor on whatever page the partial is rendered on.

When I do this however, and push to heroku and migrate the database, I'm served the error: An error occurred in the application and your page could not be served. Please try again in a few moments.

If you are the application owner, check your logs for details.

So the question is, how do I define a function for a partial?


You could do this in a before filter in your application controller like so:

...
before_filter :location

def location
    @city = request.location.city
    @state = request.location.state
end

The name of the method needs to match the symbol in the before_filter call, but other than that, you can call the method whatever you want. The method must be in the ApplicationController class though.

Clarification: This will get called before every request in your application and set these two instance variables for you, so in every view, you will always and automatically have access to @city and @state.