Last Updated: February 25, 2016
·
3.806K
· rsl

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.

2 Responses
Add your response

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

over 1 year ago ·

oh that's NICE. thanks for updating!

over 1 year ago ·