45ombq
Last Updated: February 25, 2016
·
2.861K
· rsl
D139493026e587c433ad56ae16397147

Rails 4 associations and #to_sql

I ran into a problem today where I needed to get to_sql on some association and was getting a strange result:

1.9.3-p392 :001 > Host.first.entries.to_sql
=> "SELECT \"entries\".* FROM \"entries\"  WHERE \"entries\".\"host_id\" = $1" 

The Rails 4 way to get that is:

1.9.3-p392 :002 > Host.connection.unprepared_statement{Host.first.entries.to_sql}
=> "SELECT \"entries\".* FROM \"entries\"  WHERE \"entries\".\"host_id\" = 4" 

In case you don't know whether or not you need to pass your relation through #unprepared_statement, it's safe to pass prepared statements through as well*:

1.9.3-p392 :007 > User.admin.to_sql
 => "SELECT \"users\".* FROM \"users\"  WHERE \"users\".\"admin\" = 't'" 
1.9.3-p392 :008 > Host.connection.unprepared_statement{User.admin.to_sql}
 => "SELECT \"users\".* FROM \"users\"  WHERE \"users\".\"admin\" = 't'" 

*The use case for this is library code that needs to handle whatever scope/relation it's passed without complaining.

Say Thanks
Respond

2 Responses
Add your response

8399
34e92ab37b405e5abed7e7c8bf7ba5b7

connection.unprepared_statement now takes a block, and you have to generate your sql within that block.

over 1 year ago ·
8466
D139493026e587c433ad56ae16397147

oh that's NICE. thanks for updating!

over 1 year ago ·