Blog

Oct
28
Executing SQL commands in Rails
by Alex Chee | Snippet

Most of the times, ActiveRecord’s helpers to access database info is all you need; sometimes, you want to do some hacky stuff.

For example, I had to figure out a database’s timezone and schema but I had no shell access to the server. So I ran this used Base.connection.execute and fetch_row to get the result


q=ActiveRecord::Base.connection.execute 'SELECT NOW();'
=> #
>> q.fetch_row
=> ["2009-10-20 17:30:49"]
>> Time.now
=> Tue Oct 20 10:32:02 -0700 2009
>>q.free

You can basically run any SQL query you want with these two methods. Now go crash some servers!

Note: You should also free your result to free up memory. Thanks Emmanuel.

2 Comments
October 30, 2009

You may want to free your results after fetching. See http://www.fngtps.com/2008/11/free-result-after-using-activerecord-base-connection-execute

Greets!

October 30, 2009

Thanks Emmanuel, I just updated it to reflect that.