I have a model where geocodes are calculated before the model is saved using geokit-rails plugin. I have to run a Rake task where the state field is replaced by its abbreviation in the database. I was planning to use a hash with the states and its mapped abbreviations for this task. While doing this, I dont want to calculate the geocodes again, as this will take time for each record. Here is my code:
Site.all.each do |site|
site.state = Site.convert_to_abbr(site.state)
site.save(false)
end
Site model
US_STATES = {
"Alabama" => "AL",
"Alaska" => "AK",
..
..
}
before_save :generate_lat_lon
def generate_lat_lon
puts "Entered validation"
@address = "#{address1}, #{city}, #{state}"
@location = Geokit::Geocoders::MultiGeocoder.geocode(@address)
if @location.success
self.lat = @location.lat
self.lon = @location.lng
else
self.lat = nil
self.lon = nil
end
end
def self.convert_to_abbr(state_string)
US_STATES[state_string.to_s.strip.titlecase] ? US_STATES[state_string.to_s.strip.titlecase] : state_string
end
But the problem with the above code is that, with save(false), the validations are skipped, but the validation checkings are not skipped. So, the geocodes are calculated before saving a record and this is very time consuming. Is there a method to skip validation checking also in Rails?
You could add an
attr_accessor :calculate_lat_long, and set that totruebefore anything that callssave.Your model would then have: