[英]Saving city to User Model in Rails using Geocoder
目前,我已使我的代码正常工作,以便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
现在,我正在尝试从地址获取城市。 查看文档,它提供了以下内容:
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
这总是给我一个“用户未定义的方法'city =':”错误。
看着之前在stackoverflow上问过的这个问题, Rails Geocoder出现“未定义的方法错误”,而Ruby Geocoder是否可以在reverse_geocode调用中仅返回街道名称? ,它表示我必须在上面的块中传递模型名称而不是“ obj”。 我怎么做? 我尝试了用户,结果却没用。
正如Cody所指出的,我需要首先通过迁移将城市和国家/地区字段添加到我的用户模型中。
rails g migration AddCityToUsers city:string
rails g migration AddCountryToUsers country:string
最终代码:
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
为什么不只是:
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.