2

How do I trace which SQL query did my Activerecord methods generated (eg find, where).

1
  • This answer gives you a lot of control - you get access to the queries in the app itself. Commented Oct 12, 2012 at 17:26

4 Answers 4

2

You can debug ActiveRecord queries from a console.

Hit rails console and enter:

ActiveRecord::Base.logger = Logger.new(STDOUT)
Sign up to request clarification or add additional context in comments.

Comments

1

I assume you're using Rails 3.0.x, you can do that by configuring your active record. Put this in config/environments/development.rb

# Log ActiveRecord
ActiveRecord::Base.logger = Logger.new(STDOUT) if defined?
Rails::Console

Now, every query is explained in console.

Comments

1

You can call to_sql on relation objects (like that returned when you call where) to get the SQL for those queries.

Comments

0

If you want to do it permanently (always show queries in console) just add those files:

~/.rvmrc

railsrc_path = File.expand_path('~/.railsrc')
if ( ENV['RAILS_ENV'] || defined? Rails ) && File.exist?( railsrc_path )
  begin
    load railsrc_path
  rescue Exception
    warn "Could not load: #{ railsrc_path }" # because of $!.message
  end
end

~/.railsrc

require 'active_record'

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.