开发者

How to see MySQL queries in rails console [duplicate]

This question already has answers here: How to show SQL queries run in the Rails console? (8 answers) Closed 8 years ago.

Is there a开发者_如何学编程 way to see which MySQL queries are fired from ActiveRecord in the rails console?


Yes, this can be achieved through redirecting rails log to standard output.

Write these in your console prompt:

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

Furthermore, you can put these lines in ~/.irbrc file, so that each time you don't need to manually write these 2 lines:

require 'rubygems'

if ENV.include?('RAILS_ENV') && ENV["RAILS_ENV"] == 'development'
    ActiveRecord::Base.logger = Logger.new(STDOUT)
    ActiveRecord::Base.connection_pool.clear_reloadable_connections!
end

Hope this helps...


In Rails 3+ you can use ActiveRecord::Relation’s to_sql method:

User.where(:id => 3).to_sql
#=> "SELECT \"users\".* FROM \"users\"  WHERE \"users\".\"id\" = 3"


Another way to do it for each project is inspired by http://guides.rubyonrails.org/debugging_rails_applications.html#what-is-the-logger-questionmark:

You can specify an alternative logger in your environment.rb or any environment file:

ActiveRecord::Base.logger = Logger.new("log/active_record.log") #This outputs the mysql queries to a file named active_record.log under your project's log folder.

Of course, you need to restart your server to make things work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜