开发者

In Rails, how to get the actual Query when an ActiveRecord query executes

I am 开发者_StackOverflow社区using a simple query in ActiveRecord which does something like this.

MyTable.find(:all, :conditions => {:start_date => format_time(params[:date]) })

I want to get the equivalent query that is executed in the background, perhaps using a puts statement or something similar to that. MySQL is my database.


You can see the SQL query that is executed by viewing the development log located in log/development.log. Note that the script/server command tails this log file by default.

  • In Rails 3 you can append a .to_sql method call to the end of the finder to output the SQL.

  • Alternatively, New Relic's free RPM Lite gem lets you see the SQL queries in developer mode as well as lots of other useful performance tuning information.


You can insatll mongrel

its gets you all sql queries on your terminal

or run active record query on script/console


In development mode, your DB queries are printed to the server console, you can localize the query there.


You are looking for construct_finder_sql.

>> User.send(:construct_finder_sql, {:conditions => { :username => 'joe' }})
=> "SELECT * FROM \"users\" WHERE (\"users\".\"username\" = E'joe') "

>> User.scoped(:joins => :orders, :conditions => { :username => 'joe' }).send(:construct_finder_sql, {})
=> "SELECT \"users\".* FROM \"users\"   INNER JOIN \"orders\" ON orders.user_id = users.id  WHERE (\"users\".\"username\" = E'joe') "
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜