Search code examples
ruby-on-railsdbmigrate

Update the database with new values after a migration


I have a table in my database called sessions with two columns (start_time and end_time) in it and I already have lots of data in my table. I then generated a migration:

$ rails g migration AddDurationToSessions duration:integer 

My model session.rb looks like this:

class Session < ActiveRecord::Base
   before_save :calc_duration

   def calc_duration
     return self[:end_time] - self[:start_time]
   end
end

My question is: how do I apply calc_duration to all of my older elements in my table? Do I update them manually or is there a best practice for this?


Solution

  • You can do it in migration:

    class AddDurationToSessions < ActiveRecord::Migration
      def change
        add_column :sessions, :duration, :integer
    
        # Find and update all older session record
        Session.find_each do |s|
          # new duration
          calc_duration = s.end_time - s.start_time
          # update session with new duration
          s.update(duration: calc_duration.to_i)
        end
    
      end
    end