bragboy
bragboy

Reputation: 35562

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

I am 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.

Upvotes: 4

Views: 2074

Answers (4)

Joe Van Dyk
Joe Van Dyk

Reputation: 6950

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') "

Upvotes: 0

Sachin R
Sachin R

Reputation: 11876

You can insatll mongrel

its gets you all sql queries on your terminal

or run active record query on script/console

Upvotes: 1

John Topley
John Topley

Reputation: 115392

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.

Upvotes: 7

clyfe
clyfe

Reputation: 23770

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

Upvotes: 0

Related Questions