Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I see the SQL that will be generated by a given ActiveRecord query in Ruby on Rails

I would like to see the SQL statement that a given ActiveRecord Query will generate. I recognize I can get this information from the log after the query has been issued, but I'm wondering if there is a method that can be called on and ActiveRecord Query.

For example:

SampleModel.find(:all, :select => "DISTINCT(*)", :conditions => ["`date` > #{self.date}"], :limit => 1, :order => '`date`', :group => "`date`") 

I would like to open the irb console and tack a method on the end that would show the SQL that this query will generate, but not necessarily execute the query.

like image 930
rswolff Avatar asked Aug 27 '09 23:08

rswolff


People also ask

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is Arel SQL?

Arel is a SQL abstraction that ActiveRecord uses to build SQL queries. Arel wraps each component of the SQL query language with Ruby objects and provides an expressive DSL for composing SQL queries. When using Arel, you're mainly interacting with tables ( Arel::Table ) and nodes ( Arel::Nodes::Node subclasses).

What does where return in rails?

where returns an ActiveRecord::Relation (not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation. find (and its related dynamic find_by_columnname methods) returns a single model object.


2 Answers

Similar to penger's, but works anytime in the console even after classes have been loaded and the logger has been cached:

For Rails 2:

ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT) 

For Rails 3.0.x:

ActiveRecord::Base.logger = Logger.new(STDOUT) 

For Rails >= 3.1.0 this is already done by default in consoles. In case it's too noisy and you want to turn it off you can do:

ActiveRecord::Base.logger = nil 
like image 193
gtd Avatar answered Sep 18 '22 14:09

gtd


Stick a puts query_object.class somewhere to see what type of object your working with, then lookup the docs.

For example, in Rails 3.0, scopes use ActiveRecord::Relation which has a #to_sql method. For example:

class Contact < ActiveRecord::Base   scope :frequently_contacted, where('messages_count > 10000') end 

Then, somewhere you can do:

puts Contact.frequently_contacted.to_sql 
like image 21
pathdependent Avatar answered Sep 20 '22 14:09

pathdependent