Viewing activerecord requests in rails console?

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

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

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

      

I would like to view this without doing:

u.open_documents.delete(d)

      

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

u.open_documents.to_sql

      

but when calling

u.open_documents.delete(d).to_sql

      

performs a delete (!) and generates 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?

+3


source to share


1 answer


You can call .to_sql in ActiveRecord :: Relation to see the SQL that will be executed.

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

      

Also, the console will only automatically execute the relationship (and instantiate 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 a relation without running it.

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

+8


source







All Articles