I'm trying to figure out where to add errors for validations to a rails 4 app that uses geocoder.
My model looks like this:
class Tutor < ActiveRecord::Base
belongs_to :user
validates_presence_of :user_id
geocoded_by :address do |obj, results|
if geo = results.first
obj.latitude = geo.latitude
obj.longitude = geo.longitude
obj.country = geo.country
obj.city = geo.city
obj.postalcode = geo.postal_code
obj.address = geo.address
end
end
after_validation :geocode, if: :address_changed?
end
I noticed that the if geo = result.first conditional only gets executed if the address was found successfully. I'd like to add an error message if nil is being returned. I saw that this stackoverflow thread explains that I should be using before_validation instead of after_validation, but I still don't understand where to add errors so that my view can get re-rendered and a valid geolocation can be input.
Any ideas where I should be putting this information? Thanks!
You can set in the model like this example below to validate address the geocode will be called only once when the address changed. In geocoded_by method we set explicitly to write latitude and longitude so than when the address would not be found those columns will be set to nil.
class Company < ActiveRecord::Base
geocoded_by :address do |object, results|
if results.present?
object.latitude = results.first.latitude
object.longitude = results.first.longitude
else
object.latitude = nil
object.longitude = nil
end
end
before_validation :geocode, if: :address_changed?
validates :address, presence: true
validates :found_address_presence
def found_address_presence
if latitude.blank? || longitude.blank?
errors.add(:address, "We couldn't find the address")
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With