如何对来自多个模型的地址进行地理编码?

How to Geocode address from multiple models?

我需要将用户地址geocode转换为纬度和经度以存储在数据库中。

地址table

country_id: int
state_id: int
local_address: string
latitude: float
longitude: float

我有单独的 countries and states table。 所以,要获得纬度和经度值,我需要这样的东西:

geocoded_by :address 
def address
  [local_address, state, country].compact.join(', ')
end

但问题是,这是在模型(地址 class)中完成的,我需要访问其他 tables:国家和州。

所以,想不出办法。任何工作建议表示赞赏。

在您的模型中,您需要关联到您的国家和州表 我假设您正在保存状态 ID 和 country_id

class User < ActiveRecord::Base
  belongs_to :state
  belongs_to :country

  geocoded_by :address 
  def address
    [local_address, state.name, country.name].compact.join(', ')
  end
end