你可以在模型中的两个不同位置进行地理编码吗?

时间:2015-07-24 11:00:43

标签: ruby-on-rails geocoding

所以我的模特有两个位置 - 来自'来自'和'到'地点。我怎么能geocode_by这两个得到两组经度和纬度。这就是我正在尝试的,但它只是通过'到#39;进行地理编码。 location和from_lat和from_long列都是零 - 可能只是因为' to'位置来自'来自'位置。

class Post < ActiveRecord::Base
  belongs_to :user

  geocoded_by :from_address, :latitude => :from_lat, :longitude => :from_long
  geocoded_by :to_address, :latitude => :to_lat, :longitude => :to_long
  after_validation :geocode

  def from_address
    [fromstreet, fromcity, fromstate].compact.join(', ')
  end

  def to_address
    [tostreet, tocity, tostate].compact.join(', ')
  end
end

1 个答案:

答案 0 :(得分:0)

如果有人好奇,想出如何做到这一点:

基本上只是添加了一个名为from_address_coords的新方法并将其称为before_save,因为geocoder gem只保存一组坐标 - 在这种情况下,from_address没有被保存。

class Post < ActiveRecord::Base
  belongs_to :user

  geocoded_by :to_address,   :latitude   => :to_lat,   :longitude => :to_long

  def to_address
    [tostreet, tocity, tostate].compact.join(', ')
  end

  def from_address
    [fromstreet, fromcity, fromstate].compact.join(', ')
  end

  def from_address_coords
    coords = Geocoder.coordinates(self.from_address)
    self.from_lat = coords[0]
    self.from_long = coords[1]
  end

  before_save :from_address_coords
  after_validation :geocode

end