簡體   English   中英

使用Geocoder將城市保存到Rails中的用戶模型

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM