views:

68

answers:

2

Given an ActiveRecord method or named_scope chain, is there a way to return the SQL that will get executed, without actually running it?

e.g.

Vote.positive.count.sql #=> "SELECT COUNT(*) FROM votes WHERE value > 0"

Is there a built-in way to do this or a plug-in that offers this functionality? If not, any clues to where I can start to build my own plug-in or at least a solution for this current project.

Cheers

+2  A: 

You can get information out of a named scope like so:

Vote.positive.proxy_options

As for getting the full SQL statement, ActiveRecord puts this together using a protected method called construct_finder_sql.

So you could try this:

Vote.positive.send(:construct_finder_sql, {})

The method used is different for calculation queries:

Vote.positive.send(:construct_calculation_sql, :count, :id, {})

in both cases the empty hash argument can have keys like :conditions, :order, :limit or some additional options you may discover by inspecting the bodies of these methods.

austinfromboston
A: 

It's been so long but I thought it'd be useful to point out that Rails3 will have support for this on any scope/finder/model method that ends up hitting the DB.

bjeanes