Kumar Siva
Kumar Siva

Reputation: 349

Rails activerecord where to sql

How to get sql for only condition?

Lead.where(status: 1).to_sql

SELECT `leads`.* FROM `leads` WHERE `leads`.`status` = 1

I need only the condition to sql. ie, leads.`status` = 1

Also i have default scope. From that i need only that scope to sql

Upvotes: 5

Views: 1935

Answers (2)

TomMix
TomMix

Reputation: 21

The following should work:

Lead.where(status: 1).values[:where].ast.to_sql

We are in the internals of ActiveRecord here, so it comes without guarantee of course.

Upvotes: 0

Tom Copeland
Tom Copeland

Reputation: 1271

You can use Arel::SelectManager#where_sql:

>> Lead.where(status: 1).arel.where_sql
=> "WHERE \"leads\".\"status\" = $1"

Upvotes: 10

Related Questions