Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3. How to perform a save action on all records?

I have a model called shipments. I added some columns to the shipments table and there are some columns that are supposed to be calculated before save. So now I have to edit every record and hit update in order for the new columns to calculate and add the data.

So is there a way to perform a global save on all shipment records so the data can be added?

before_save :default_values
  def default_values
    self.volume = 1 unless self.volume
    self.kilograms = 1 unless self.kilograms
    self.status = "Open" if self.status.blank?
      if self.mode == "Air"
        self.estimated_transit_time = self.etd_origin + 7.days
        self.eta_place_of_delivery = self.etd_origin + 7.days
      else
        self.estimated_transit_time = self.etd_origin + (Place.find_by_city(self.place_of_loading).transit_time).days
        self.eta_place_of_delivery = self.etd_origin + (self.estimated_transit_time).days
      end
  end
like image 396
leonel Avatar asked Jan 19 '12 14:01

leonel


2 Answers

One liner:

Shipment.find_each(&:save)
like image 166
Victor Avatar answered Sep 20 '22 11:09

Victor


Load your data by batch. Never load all at once

Shipment.find_each(:batch_size => 1000) do |shipment|
  shipment.save!
end

Then when you have to calculate some fields after a migration or something else. Simply add this job to your migration.

like image 33
basgys Avatar answered Sep 16 '22 11:09

basgys