You learn something new everyday! Of course it’s in the documentation, but it’s easy to overlook features.
As you may or may not know, ActiveRecord lets you specify conditions in a multitude of ways. Take the first example from the docs:
authenticate_unsafely is an aptly named method. Do you see the problem? Yup, you’re opening yourself up for SQL injection. So that’s NOT the way to do things. Instead ActiveRecord allows you to use placeholders like the second example from the docs:
Using that syntax, the conditions are sanitized so when the query is sent to your database, no nasty injection will occur.
As an aside, there’s an even easier way to perform a sanitized query like the last example:
That’s a nice shortcut for when you have a bunch of AND conditions.
I was writing a WHERE clause that looked for a value in multiple columns using an OR instead of an AND. My first attempt looked something like this:
Yuck. Not very DRY. I figured there had to be a better way, and I was correct.
Named Bind Variables
It turns out that ActiveRecord will allow you to use variables in your conditions. This turns my ugly query from above into this little gem:
W00t! I wasn’t aware that named bind variables existed. Of course my little example is DRY now, but how often do you write a query like mine? Not often (though I did come across this example while writing this post). As I’m sure you guessed, there are better uses for named conditions. Take a really long query (also from the docs), e.g.:
Imagine that using the question mark syntax. Sure you could do it, but with the variables in the query, it is better for readability.
I figured that if I just discovered this, there must be others that have done the same, and I was right! There’s so much stuff you can do; you can’t know everything. Thankfully there are the ActiveRecord API Docs, but of course finding things in documentation isn’t always the easiest. I hope this blog post will help guide others to the docs.