Friday, July 30, 2010

Configure Rails console to show ActiveRecord SQL

ActiveRecord, like all other ORMs abstracts away your database and its associated SQL so that you're effectively just dealing with objects. The abstraction method is determined by the ORM and it sometimes makes mistakes.

Most recently, I built a self referencing ActiveRecord object in order to model a hierarchical relationship. Unfortunately, hierarchies are not easily represented using a relational database because the database consists only of flat tables. There are various ways to represent hierarchy in a table.

However you choose to model your data, you need to make sure that ActiveRecord isn't doing something stupid when you ask for your data.

I kept looking this piece of code on the net so I decided to just paste it here so that I'd remember it in the future.

Add this to the ~/.irbrc file:

if ENV['RAILS_ENV']
# Called after the irb session is initialized and Rails has been loaded
IRB.conf[:IRB_RC] = Proc.new do
logger = Logger.new(STDOUT)
ActiveRecord::Base.logger = logger
ActiveResource::Base.logger = logger
end
end


Now, you can see what ActiveRecord is doing whenever you perform a query.