[英]Saving city to User Model in Rails using Geocoder
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): 目前,我已使我的代码正常工作,以便Geocoder获取用户的IP地址并保存物理地址(以及用于开发的硬编码IP地址):
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. 这总是给我一个“用户未定义的方法'city =':”错误。
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? 看着之前在stackoverflow上问过的这个问题, Rails Geocoder出现“未定义的方法错误”,而Ruby Geocoder是否可以在reverse_geocode调用中仅返回街道名称? , it says that I have to pass the model name instead of "obj" in the block above.
,它表示我必须在上面的块中传递模型名称而不是“ obj”。 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. 正如Cody所指出的,我需要首先通过迁移将城市和国家/地区字段添加到我的用户模型中。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.