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.
精彩评论