aaandre
aaandre

Reputation: 2512

Preview activerecord queries in rails console?

Is there a way to preview queries in the Rails console without executing them?

Edit: I would like to be able to preview destructive queries without executing them:

u = User.first
d = User.open_documents.first

I'd like to preview this without execution:

u.open_documents.delete(d)

The proposed answer of adding .to_sql at the end of the expression works for

u.open_documents.to_sql

but when called on

u.open_documents.delete(d).to_sql

executes the delete(!) and produces an error:

NoMethodError: undefined method `to_sql' for #<Array:0x585e4a8>

when called like this, I also get an error:

u.open_documents.first.to_sql
NoMethodError: undefined method `to_sql' for #<Array:0x585e4a8>

Any ideas for a workaround?

Upvotes: 4

Views: 3643

Answers (1)

MrTheWalrus
MrTheWalrus

Reputation: 9700

You can call .to_sql on an ActiveRecord::Relation to see the SQL that would be executed.

User.where(:id => 4).to_sql
 => "SELECT \"users\".* FROM \"users\"  WHERE \"users\".\"id\" = 4" 

Also, the console will only automatically execute the relation (and instantiate the objects) if it's the last command on the line, so you can do this:

relation = User.where(:id => 4); 1
=> 1

and thus set a variable to the relation without running it.

I'm not actually sure which of these two you wanted to do, but they're both handy tricks.

Upvotes: 9

Related Questions