【问题标题】:Saving city to User Model in Rails using Geocoder使用地理编码器将城市保存到 Rails 中的用户模型
【发布时间】:2014-03-28 06:25:38
【问题描述】:

我的代码目前正在运行,以便地理编码器获取用户的 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=' for User:”错误。

查看之前在 stackoverflow 上提出的这个问题,Rails Geocoder "undefined method error"Can Ruby Geocoder return just the street name on reverse_geocode calls?,它说我必须在上面的块中传递模型名称而不是“obj”。我怎么做?我尝试了用户,结果,但没有奏效。

【问题讨论】:

  • 您的User 模型是否还有city 字段?
  • 不,我是否需要将其添加为迁移,即 rails g migration AddCityToUsers city:string?我只希望 user.location 成为城市。
  • 好的,好像可以了。

标签: ruby-on-rails model rails-geocoder


【解决方案1】:

正如 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

【讨论】:

    【解决方案2】:

    为什么不只是:

    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
    

    【讨论】:

    • 这行得通,但在我的情况下,位置可能是两件事之一,它首先用于 Facebook 的位置,然后再通过 IP 地址查找。
    猜你喜欢
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多