2

I've been trying to write some code that automatically detects the IP address of the website visitor and displays the corresponding city. I thought this would be as simple as using Geocoder to detect the IP then display the corresponding city, however I am having no success.

I've been looking through documentation that claims to be compatible with IP addresses, but either I'm doing something incorrectly, or the documentation is wrong: http://rdoc.info/github/alexreisner/geocoder/master/frames

I have this in my location.rb model, which supposedly provides data such as result.city as a string.

class Location < ActiveRecord::Base
  attr_accessible :address, :latitude, :longitude

  reverse_geocoded_by :lat, :lon do |obj,results|
      if geo = results.first
        obj.city    = geo.city
        obj.zipcode = geo.postal_code
        obj.country = geo.country_code
      end
    end
    after_validation :reverse_geocode

end

So I added @city = result.city to my locations_controller.rb

def index
    @locations = Location.all
    @city = result.city
  end

Then to test that it worked I put <%= @city %> into my index.html.erb in locations.

Upon rendering the page I receive an error in my controller, stating that 'result' has not been defined:

undefined local variable or method `result' for #<LocationsController:0x007faf9d5009e8>

app/controllers/locations_controller.rb:7:in `index'

Where am I going wrong? Or why doesn't the model function as described?

Laser
  • 5,085
  • 4
  • 34
  • 48
  • I got IP now by going (at)ip = request.remote_ip in the index in the locations controller, but now I'm trying to define (at)city in the index to find the corresponding city for the ip address. Thanks. – Laser Apr 11 '12 at 18:53
  • Sorry for all the noise, I realized that (at)city = request.location.city was displaying nothing because I was running a local server, upon deployment to heroku it displays what is intended. – Laser Apr 11 '12 at 19:03
  • 3
    Since your problem is solved, you can either delete the question or add an answer and accept it (if you think the question/answer could be useful to someone else). – Justin D. Apr 11 '12 at 20:13
  • Hi @Laser, I know this is a long time ago but if you still remember how to do it would you make a post or tell me how to do the same thing but in Rails 4? I'm searching for a similar way to do what you've done (http://stackoverflow.com/q/32102967/4484024) – Henry Lee Aug 19 '15 at 20:17
  • @HenryLee I've put a solution to the question you linked. – Laser Aug 20 '15 at 06:48

0 Answers0