我正在使用Sinatra ruby框架。我有一个交付模型(见下文)。我正在使用ActiveRecord的geocoder gem。
我的架构中有纬度和经度字段。
当我使用控制台获取地理编码时:
Geocoder.search delivery.address
我收到了谷歌API的回复。
但它并没有填充lat \ lon字段。我无法想象为什么。
我在app.rb中使用API密钥,如下所示:
Geocoder.configure(
api_key: ENV['GEOCODER_API_KEY']
)
我知道密钥有效,因为我每秒都会收到相对较多API调用的响应。(如果没有api密钥,它每隔10秒就会调用一次,或者它会返回配额错误)
这似乎是一个简单的问题,但我无法弄明白。非常感谢帮助。
Delivery.rb
require 'sinatra/shopify-sinatra-app'
require 'geocoder'
# This is the delivery model. It holds all of the data
# associated with the delivery such as the orrder and shop it belongs to .
class Delivery < ActiveRecord::Base
extend Geocoder::Model::ActiveRecord
has_many :delivery_states, dependent: :destroy
belongs_to :shop
belongs_to :fulfillment_service
validates :order_id, uniqueness: true, presence: true
has_one :courier, through: :fulfillment_service
#after_create :add_delivery_state
attr_accessor :latitude, :longitude
#geocoder setup
geocoded_by :address
after_validation :geocode#, :if => lambda{ |obj| obj.address1_changed? || obj.city_changed? || obj.province_changed? || obj.country_changed? }
def address
#check address1 is not a variation of POB
addr = address1 unless address1.match(/(?:P(?:ost(?:al)?)?[\.\-\s]*(?:(?:O(?:ffice)?[\.\-\s]*)?B(?:ox|in|\b|\d)|o(?:ffice|\b)(?:[-\s]*\d)|code)|box[-\s\b]*\d)/i)
[addr, city, province, country].join(',')
end
def add_delivery_state(status=0,ref_number=nil)
if self.delivery_states.count>0
ref_number = self.delivery_states.last.courier_reference unless ref_number
else
ref_number = 0 unless ref_number
end
self.delivery_states<<DeliveryState.new(delivery_status:status,courier_reference:ref_number)
end
def delivery_state
self.delivery_states.last.delivery_status
end
def courier_reference
self.delivery_states.count>0 ? self.delivery_states.last.courier_reference : "0"
end
end