0

我希望允许我的模型通过full_street_addressreverse_geocoded_by :latitude:longitude进行地理编码,以便我可以调用 Address.near 并通过一种或另一种方式获取它们。

这似乎可行,但这种方法会导致潜在问题还是正确?

这是我的代码:

class Address < ApplicationRecord
  geocoded_by :full_street_address
  after_validation :geocode
  reverse_geocoded_by :latitude, :longitude

  def full_street_address
    self.street + self.city + self.country
  end
end
4

2 回答 2

3

是的,您可以使用它,默认情况下,如果提供地址和 lat/lng 地址,它将覆盖。

您可以分成两个类,并Address.near([:lat, :lng])在保存后稍后调用。

楷模

- /model/address.rb
   class Address < ApplicationRecord
      #any association/validations here

      geocoded_by :full_street_address

      #by default it will save full address to address field. 
      reverse_geocoded_by :latitude, :longitude do |obj,results|
        if geo = results.first
            #customize as you want
              obj.street  = geo.address.split(',')[0]
              obj.city    = geo.city
              obj.zip     = geo.postal_code
              obj.state   = geo.state
        end
      end

      def full_street_address
         self.street + self.city + self.country
      end
   end

- /model/address/with_address.rb
   class Address::WithAddress < Address
      after_validation :geocode
   end

- /model/address/with_lat_lng.rb
   class Address::WithLatLng < Address
     after_validation :reverse_geocode
   end

控制器

   address = Address::WithLatLng.create(latitude: 40.5236803, longitude: -80.2249546)
   # returns: will save lat/lng and address/city/state/zip fields saved from api
   address.full_street_address
   #or
   address = Address::WithAddress.create(address: "601 fake st.", city: "brooklyn", state: "ny", zip: "11220")
   # returns: will save address and latitude:, longitude: will fetch from api.
   address.full_street_address
于 2018-03-14T08:15:23.903 回答
1

它有效,但它是多余的。那是因为geocoded_by您拥有完整的街道地址并获得纬度和经度,这就是您的情况。但是reverse_geocoded_by允许你从一个纬度和经度中获取一个地址,但是你已经有了它。

只需删除reverse_geocoded_byand 如果您想使用纬度和经度,只需调用数据库中的字段:self.latitudeand self.longitude,例如,您应该定义的字段(并且地理编码服务正在为您填写)。

于 2018-03-13T22:13:05.417 回答