I’m writing a rails migration that populates a premium_from datetime column in a postgres table.
I have no problem with the population, but I’m stuck writing a rollback method for the migration, as either rails or postgres is seemingly just doing nothing when I attempt to change the datetime attribute back to nil. I haven’t been able to get any useful error messages out either, so I’m not at all sure what is happening.
Here’s my most recent iteration (I tried acting on the accounts individually out of desperation, as nothing else seems to work either):
def self.down
Account.where('premium_from is not null').each do |a|
a.update_attribute(:premium_from, 'null')
end
end
This merrily runs for about 7 seconds and then leaves me with all the populated premium_from entries still intact, and I’m unable to find anything useful in google either.
Does anybody know how to set datetime colum entries to nil in postgres?
Or am I just overlooking something obvious?
Edit: up looks like this
csv.each do |row|
if account = Account.premium.find_by_name(row.first)
# This .find is necessary because .premium uses a join, meaning that it returns
# read-only objects
Account.find(account.id).update_attribute(:premium_from, Time.parse(row.last))
end
end
First of all, I would avoid referring to the
Accountclass inside your migration, unless you have defined anAccountclass in the migration itself. This is always the sensible way to go because you may refactor theAccountclass and call it something different in the future, and in then this migration won’t run. Something likeclass Account < ActiveRecord::Base; endshould do.Having that out of the way, I would recommend just using SQL in this case. It’s simple enough and will perform way better. There’s no need to bring all those records in, and build AR objects, just to issue updates. Here’s how I’d do it: