How can I skip the validation checks(not even entering the validation checks) in ActiveRecord?
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 t开发者_StackOverflowhis 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 to true
before anything that calls save
.
Your model would then have:
before_save :generate_lat_lon, :if => :calculate_lat_lon
You could use
site.send(:update_without_callbacks)
http://ackbar.rubyforge.org/classes/ActiveRecord/Base.html#M000082
精彩评论