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.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.