Bustikiller
Bustikiller

Reputation: 2508

Activerecord query to SQL

I would like to know if there is a way to obtain the SQL query from an ActiveRecord query without actually performing the query. I am looking for something like this:

get_sql_query(Item.where(status: 'open')) 
# SELECT * FROM items WHERE status="open"

Upvotes: 1

Views: 338

Answers (1)

Noman Ur Rehman
Noman Ur Rehman

Reputation: 6957

You can use the to_sql method like this:

User.where(name: 'Oscar').to_sql
# returns SELECT "users".* FROM "users"  WHERE "users"."name" = 'Oscar'

In your case, it would be:

Item.where(status: 'open').to_sql

Upvotes: 3

Related Questions