http://podloni.co.cc Rebecca’s Ramblings » ActiveRecord

Archive for the ‘ActiveRecord’ Category

“Time” columns and Rails

Thursday, January 3rd, 2008

In SQL, there is a data type TIME which holds time of day information without date information. There is no equivalent class in Ruby. Rails (ActiveRecord) deals with this by adding some dummy date data and using the standard Ruby Time class. Currently the dummy date used is 2000-01-01, though since I can’t find any documentation on this, I guess it could be changed to something else in the future.

This means you can run into some odd issues if you aren’t careful when comparing values from SQL TIME columns with times in your code.

For example, if you have a record r in your database with the value “13:30:00″ stored in a column called arrival_time of SQL data type TIME:

Time.parse("2000-01-01 13:30") == r.arrival_time       # unless the dummy date AR uses has changed

"13:30:00" == r.arrival_time_before_type_cast

Time.parse("13:30") != r.arrival_time         # unless today is 1st January 2000

What happens when a migration fails

Friday, August 3rd, 2007

So… you’re writing a migration, you think you’ve got it right - time to try it out. You run
rake db:migrate
to apply your migration, and it doesn’t work.

Your database has some of the changes from the migration in it, and the rest aren’t there. How do you get it back into the state it was in before you attempted the migration?

You might think that
rake db:migrate VERSION=nn
(where nn is the migration number before the one that failed)
would do the job, presuming that your failed migration’s self.down method runs the statements to rollback your changes in the same order as the self.up method makes the changes.

Unfortunately, nothing happens. Rails knows it didn’t complete the migration, so has left the current schema version number as at the end of the last migration which did complete.

At this point, you are faced with opening up your database and reverting the changes that did get made manually…

There is, however, a patch in rails-trac to fix this issue - if you are using a database that supports transactions round data definition statements (such as Postgres). Once installed, your migration is wrapped in a transaction, which is rolled back if any errors occur. Yippee!