I had the same issue.
Software |
Version |
Ruby |
v2.6.6 |
Rails |
v5.2.5 |
Geocoder |
v1.6.4 |
My approach was to give the geocode_by
method a block, as mentioned in the documentation section Custom Result Handling.
In my case I ended up with the following piece of code. My Model name is Job
. If the request to the API returns empty, I make another request, with only the field I want.
geocoded_by :full_address do |job, results|
if results.empty?
geo = Geocoder.search(job.city).first
if geo.present?
job.latitude = geo.latitude
job.longitude = geo.longitude
end
else
job.latitude = results.first.latitude
job.longitude = results.first.longitude
end
end
after_validation :geocode, if: ->(job) { job.will_save_change_to_address? || job.will_save_change_to_city? }