Getting close to the database in Rails

Sometimes ActiveRecord wraps your data up too much, and you don’t want or need all that convenient but processor-cycle consuming abstraction.We had a case where we wanted to delete nearly 3 million records from our database. The conditions for deletion were a little complex, and writing a single SQL query for it was not practical.So it’s nice to do it in Ruby, but instantiating 3m ActiveRecord objects is just not an option. Well, we didn’t need to – you can get data more directly from the database by talking directly to the (mysql in our case) connection.Here’s how to get a list of ids from the database that were last updated last year.

result = ModelClass.connection.execute("SELECT id FROM table            WHERE updated_at < '2008-01-01'")
ids = []result.each {|row|  ids << row[0].to_i}

Then you can go through the ids and do what you like with them, perhaps compare them to other lists of ids from other tables (which is what we did).Deleting the records is easy, just use ModelClass.delete(the_id) which works without instantiating an object. Use with care!

Breakage / Fixage in Rails 2.0.2

Apart from well known stuff like start_form_tag being deprecated, these things broke for us with Rails 2.0.2:1. Super is no longer called in tests. Use setup_with_fixtures instead, which will work in rails 2.0.2 and future versions where the bug is fixed.2. The paths to partials used by ActionMailer have changed – now we must use “controllername/partialname” as opposed to “../controllername/partialname”3. The handling of plusses in urls has changed. It probably changed in this changeset. The result is that passing a + in a url path no longer gets translated to a space in the handling done by rails. So now we have correct handling according to RFC2396.