Generating And Executing SQL
Rails' ActiveRecord can easily support 90% of the querying we do against the tables in our database. However, there is the occasional exceptional query that is more easily written in SQL -- perhaps that query cannot even be written with the ActiveRecord DSL. For these instances, we need a way to generate and execute SQL safely. The sanitize_sql_array
method is invaluable for this.
First, let's get a connection and some variables that we can use downstream in our query.
Now, we are ready to safely generate our SQL query as a string. We have to use send
because it is not publicly available. Generally, this is frowned upon, but in my opinion it is worth breaking the private interface to ensure our SQL is sanitized.
Lastly, we can execute the query with our connection and inspect the results.
Last updated