Free result after using ActiveRecord::Base.connection.execute

Manfred Stienstra

Just a quick warning: when you use ActiveRecord::Base.connection.execute you get a Mysql::Result instance, this is a very thin wrapper around the actual result returned from libmysqlclient. This means you have to free the memory of the result table, failing to do so will result in erratic query times because somewhere a garbage collector will do it for you.

class Person < ActiveRecord::Base
  # Returns the last name of someone given the ID
  def self.last_name(id)
    result = connection.execute("SELECT last_name FROM people" +
      " WHERE id = %d" % id)
    last_name = result.fetch_row.first

When you want to select a number of entire rows, you can use the already safe select_rows.

You’re reading an archived weblog post that was originally published on our website.