0

I wrote a migration script to update all previous records in ActiveRecord.

class UpdateListCompletedAtFields < ActiveRecord::Migration

def up
    Car.find_each do |car|
        if car.list_car_step_3_finished?
            car.list_completed_at = Time.now
            puts "Car #{car.id} list_completed, updating list_completed_at: #{car.list_completed_at}"
        end
    end
  end

end

when I run the migration script, the puts message output the field car.list_completed_at correctly, but when I then get into rails console (after I extied) and try to check the data, the migration did not persist. I am wondering if I am missing anything?

Car.all.map{|m| [m.list_car_step_3_finished, m.list_completed_at]}
=>[[true, nil], [true, nil], [nil, nil], [nil, nil], [nil, nil], [nil, nil], [nil, nil], [nil, nil], [nil, nil], [true, nil], [nil, nil]]
Chris Yeung
  • 2,613
  • 6
  • 34
  • 57

2 Answers2

2

You forget to save car record:

car.list_completed_at = Time.now
car.save
# (...)
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
  • Hi.I'm actually wondering why you deleted your answer in this question http://stackoverflow.com/questions/22629261/retrieving-a-single-record-from-an-activerecord-rails-query/22630078#22630078 though its correct and you are the first person who answered.Forgive me if its not the correct way to communicate with you. – Pavan Mar 25 '14 at 11:16
  • @Pavan I din't read the question carefully, so my answer was simply incorrect. – Marek Lipka Mar 25 '14 at 11:17
  • But your answer is right and see the remaining answers.those all eually same as your answer. – Pavan Mar 25 '14 at 11:19
  • Yeah! you are right.But according to the title of the question,your answer and those remaining all are right! Except that exception part where the OP asked 'if there is more than 1' :) – Pavan Mar 25 '14 at 11:23
0

Use update_attribute to update the database

if car.list_car_step_3_finished?
   car.update_attribute(:list_completed_at, Time.now)
   puts "Car #{car.id} list_completed, updating list_completed_at:#car.list_completed_at}"
end  
Kimooz
  • 941
  • 9
  • 10