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:
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:
3. Knowing your 'self'
Instead of having to do something like this:
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:
Hopefully some of these are helpful. I plan on adding more posts similar to this as I learn more.
Front-End Developer and Ruby on Rails Newbie