[英]Validating Longitude/Latitude with Geocoder Gem
I'm using the Geocoder gem in rails to generate latitudes/longitudes from an address. 我在轨道中使用Geocoder宝石从地址生成纬度/经度。 I've implemented validations based on the following stack overflow question: 我已经根据以下堆栈溢出问题实施了验证:
Validating with Geocoder Gem 使用Geocoder宝石进行验证
Model 模型
class Location < ActiveRecord::Base
attr_accessible :address1,
:country,
:latitude,
:longitude,
:name
validates :latitude, :presence => {message: "Not a valid location on Google Maps, please check name address & country fields" }
geocoded_by :address
after_validation :geocode, :if => :address_changed?
def address
[name, address1, country].compact.join(' ')
end
def address_changed?
attrs = %w(name address1 country)
attrs.any?{|a| send "#{a}_changed?"}
end
end
My issue is that when a user edits their valid address to an invalid address the geocoder gem doesn't update the longitude/latitude fields. 我的问题是,当用户将其有效地址编辑为无效地址时,地理编码器gem不会更新经度/纬度字段。 Therefore the longitude/latitudes remain valid even though the address isn't. 因此,即使地址无效,经度/纬度仍然有效。
I'm new to rails and tried to find a way to set the longitude/latitude fields to nil before running the geocoder but couldn't find a method that worked. 我是Rails的新手,尝试找到一种方法来运行Geocoder之前将经度/纬度字段设置为nil,但找不到有效的方法。 For example I tried to add the following into my edit form: 例如,我尝试将以下内容添加到我的编辑表单中:
<%= f.hidden_field :longitude, value: nil %>
<%= f.hidden_field :longitude, value: nil %>
Active Record provides a before_validation callback . Active Record提供了before_validation回调 。
before_validation :set_coords_to_nil, :if => :address_changed?
private
def set_coords_to_nil
self.latitude = nil
self.longitude = nil
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.