Search code examples
sqlruby-on-railsrubyruby-on-rails-3rake

How to check SQL commands executed using rake in Ruby on Rails


I want to count the votes a user has given to an article and save it somewhere.

I want to check all the SQL INSERT or CREATE lines executed when we do something like:

>$ bundle exec rake db:reset
>$ bundle exec rake db:seed
>$ bundle exec rake test:prepare

Is there a way I can check the SQL commands in Ruby on Rails?


Solution

  • You can add a custom Rake task and use it whenever you need to log the SQL output:

    task log: :environment do
      ActiveRecord::Base.logger = Logger.new(STDOUT)
    end
    

    Now you can run:

    bundle exec rake log db:reset
    bundle exec rake log db:seed
    bundle exec rake log test:prepare
    

    See "Is it possible to output the SQL change scripts that 'rake db:migrate' produces?"