0

I've currently got my code working so that the Geocoder takes the user's IP address and saves the physical (along with a hard-coded IP address for development):

class User < ActiveRecord::Base
    geocoded_by :ip_address
    after_validation :geocode

    reverse_geocoded_by :latitude, :longitude
    after_validation :reverse_geocode

    def self.remote_ip
        if $request.remote_ip == '127.0.0.1'
          '111.11.333.666'
        else
          $request.remote_ip
        end
    end  

  user.ip_address = remote_ip
  user.location = user.address

Now I'm trying to get the city from the address. Looking at the docs, it provides this:

reverse_geocoded_by :latitude, :longitude 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

This keeps giving me an "undefined method `city=' for User:" error.

Looking at this question asked previously on stackoverflow, Rails Geocoder "undefined method error" and Can Ruby Geocoder return just the street name on reverse_geocode calls?, it says that I have to pass the model name instead of "obj" in the block above. How do I do that? I tried user,results but that didn't work.

Community
  • 1
  • 1
Amir
  • 281
  • 5
  • 15

2 Answers2

0

As Cody pointed out, I needed to add the city and country fields to my User model via migrations first.

 rails g migration AddCityToUsers city:string
 rails g migration AddCountryToUsers country:string

Final code:

reverse_geocoded_by :latitude, :longitude do |obj,results|
if geo = results.first
  obj.city    = geo.city
  obj.country    = geo.country
end
end
after_validation :reverse_geocode

user.location = user.city + ", " + user.country
Amir
  • 281
  • 5
  • 15
0

Why not just:

reverse_geocoded_by :latitude, :longitude do |obj,results|
  if geo = results.first
    obj.city = geo.city
    obj.country = geo.country
    # make a combined field with both city/country
    obj.location = geo.city + ", " + geo.country
  end
end
after_validation :reverse_geocode
Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
  • That works, but in my case location can be one of 2 things, it goes for their location of Facebook first before looking it up by IP address. – Amir Mar 28 '14 at 08:17