Rails console and ActiveRecord SQL queries – Rails quick tips

Rails console and ActiveRecord logger – Rails 3

Well, there are many many times (in fact always :P) that you want active record sql queries to log into STDOUT and especially when you are working in the rails console. I didn’t know how to do this and after a while of Google searching I stumbled upon this command that you type every time you open the rails console:

ActiveRecord::Base.logger = Logger.new(STDOUT)

That was pretty sweet when I saw this little command working (my sql queries were shown into the console :)) but ended up a little annoying having to type this every time I open my console. The solution is apparent if you try this in a rails console

# rails c
# => "script/rails"

Thus inside the console the $0 has value "script/rails". Therefore inside your environment.rb file you can write:

if "script/rails" == $0
  ActiveRecord::Base.logger = Logger.new(STDOUT)

and get ActiveRecord sql queries to log to STDOUT everytime you use the console. If you don’t wrap ActiveRecord::Base.logger = Logger.new(STDOUT) inside this if statement then you will always use STDOUT as the ActiveRecord logging and you don’t want that in any way!

2 Comments Rails console and ActiveRecord SQL queries – Rails quick tips

Leave a Reply

Your email address will not be published. Required fields are marked *