Rails Code Snippet Starter Kit

Sometimes one piece of code in a language doesn't translate verbatim to another. Sometimes 5 lines of code can be written in 1. That is what this post is about - the snippets of code you lean on during the early stages of your Rails learning.

1. Avoiding use of if/else/unless when unnecessary

Ever heard of a ternary operator? No? It seems like one of those names that no one remembers and every one just creates their own name for it. There's a good chance you've seen one before because they're quite handy in the right situation. Here's what they look like:

This is the block of code it replaces:

Copy/paste-able snippet of the ternary operator example.

2. Use the tools Rails blessed you with

Rails provides a lot of cool, built-in functionality for accessing your models. Before you re-invent the wheel, make sure Rails doesn't have something in place for you to use. For me, I wrote a lot of duplicate code in the beginning (and still do unfortunately) because I didn't know all the tools at my disposal. So here's a helpful one, the Rails 'find_by' method. Instead of writing out an SQL-like statement for your model, use the 'find_by' method like this:

Which is equivalent to:

Copy/paste-able snippet of the 'find_by' method example.

3. Knowing your 'self'

Pretty cheesy heading for this one. Sorry, I couldn't resist myself. Using 'self' can be confusing at first, like when to use 'this' in JavaScript, but it's something you need to get under your belt and once you do it becomes common practice. Here is a simple example:

Instead of having to do something like this:

Copy/paste-able snippet of the 'find_by' method example.

4. How to use variables in database look-ups

This is one that caused me to go back and re-write a lot of my code. Not only is it good practice, but there are serious security concerns around using variables in database queries. If someone knows their way around escaping values, you run into some nasty potential SQL injection problems. This might not be news to you, but if you've never been told, here's the right way:

And here's the wrong way:

Copy/paste-able snippet of using variables in database queries.

Hopefully some of these are helpful. I plan on adding more posts similar to this as I learn more.

Dan
Front-End Developer and Ruby on Rails Newbie
dan@thredup.com