Friday, November 18, 2011

ActiveRecord generate sql query on ruby console


Most of the times I want to see the active record generated sql queries in console and specially when I am working on ruby console.
I have try to search on google and I found some code like
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.clear_active_connections!

This code we need to place in application.rb, as this code is set all active_record loggor activity for 'STDOUT'.

But this code was recomanded for rails-3. It may not work on rails 2x.

To view sql query in ruby console for rails 2x we need to run following code on console.
require 'logger'
if ENV.include?('RAILS_ENV')&&
!Object.const_defined?('RAILS_DEFAULT_LOGGER')
   Object.const_set('RAILS_DEFAULT_LOGGER', Logger.new(STDOUT))
else
   ActiveRecord::Base.logger = Logger.new(STDOUT)
end

Or we can create .irbrc file and put that code in this file, So we do not need to run above commands every time.

Now on ruby console we can view generated sql query against 'ActiveRecord' methods.