Rails validation issue with before_validation
I'm still fairly new to rails so I'm not sure what I'm missing here.
I'm using GeoKit to geocode an address upon saving. I have a method that geocodes an address and if it fails to find it, it adds an error to the errors list. I've tested it in the console and it is failing on the geocode (presumably adding the error) but still saving successfully.
acts_as_mappable
before_validation_on_create :geocode_address
before_validation_on_update :geocode_address
validates_presence_of :street
validates_presence_of :city
validates_presence_of :state
validates_presence_of :zip
validates_presence_of :name
validates_uniqueness_of :name
def geocode_address
geo=Geokit::Geocoders::MultiGeocoder.geocode ("#{street}, #{city}, #{state}, #{zip}")
puts "geocoded: #{stre开发者_如何学运维et}, #{city}, #{state}, #{zip}"
if geo.success
self.lat, self.lng = geo.lat,geo.lng
else
errors.add(:street, "Could not Geocode address")
end
puts "geo status: #{geo.success}"
end
Any help would be greatly appreciated, thanks :)
A before_validation
hook is not the same as an actual validation. You are trying to combine the two here. You still want to try to create the geocode in your hook, but use a separate validation to actually ensure that it's correct, and do the errors.add
there.
精彩评论