Helper to print out your ActiveRecord SQL
Tue, Mar 15, 2016Sometime you just want to see the SQL statement that your ActiveRecord magically generate, without going through hundreds of lines in your log file. An easy way to do that is to assign the ActiveRecord::Base.logger
to a new Logger
that prints to the STDOUT
, and then change it back to the old logger so it doesn’t keep printing out SQL for the rest of your code.
ol = ActiveRecord::Base.logger
ActiveRecord::Base.logger = Logger.new(dest)
User.where(type: 'admin').limit(10).to_a
ActiveRecord::Base.logger = ol
We can go further and add this helper method to your ActiveRecord::Base
.
module PrintOutSql
def print_sql(dest = STDOUT)
ol = ActiveRecord::Base.logger
ActiveRecord::Base.logger = Logger.new(dest)
yield
ActiveRecord::Base.logger = ol
end
end
ActiveRecord::Base.extend(PrintOutSql)
So you can just wrap your code inside the print_sql block, and it will print out all SQL statements that were executed inside that block only.
# assuming User is an ActiveRecord::Base
User.print_sql do
User.where(type: 'admin').limit(10).to_a
end