Welcome to Giant Robots Smashing Into Other Giant Robots — a weblog about development, business, design and technology — written by thoughtbot.
extra action
The following code samples, taken from a controller, demonstrate different ways of creating a Referral with or without a Team. A Referral represents one user inviting another eventual user to the site and optionally to their Team. Whether this is the best way to model this doesn’t matter, right now, I just want to take a look at a couple different code samples.
1 2 3 4 5 6 7 8 |
if session[:team_id].blank? Referral.create(:user => current_user, :referer => referer) else Referral.create(:user => current_user, :referer => referer, :team => Team.find(session[:team_id])) end |
Very straightforward, nothing special there. Here’s another version:
1 2 3 |
Referral.create(:user => current_user, :referer => referer, :team => Team.find_by_id(session[:team_id])) |
Much more succinct by relying on the #find_by_id hack. I really don’t like that #find_by_id. To me it’s lazy coding along the lines of this:
1 |
<%= h user.address.street rescue '' %> |
instead of putting a conditional:
1 2 3 |
<% unless user.address.nil? %> <%= h user.address.street %> <% end %> |
Nobody likes conditional logic but come on.
Ok, let’s look at another version.
1 2 3 4 5 6 |
unless session[:team_id].blank? team = Team.find session[:team_id] end Referral.create(:user => current_user, :referer => referer, :team => team) |
Now you might think that’s not going to work when that condition is true, but through some crazy hack in Ruby it does not raise an error. I didn’t realize about that until recently, not sure how commonly known it is. And for that reason I’m going to have to outlaw this version as being way too tricky.
What do you guys think?
About this entry
You're reading an entry on GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS, the company weblog of thoughtbot, inc.
- Author:
- Jared Carroll
- Published:
- March 27th 08:07 PM
- Updated:
- April 1st 10:49 AM
- Sections:
- Development Technology
thoughtbot is hiring
We are hiring web developers and web designers in both Boston and New York, NY.
What are we up to?
We built Shoulda, an eclectic set of additions to Test::Unit; Paperclip to manage uploaded files without hassle; Jester, a REST/ActiveResource client library written in Javascript, and Squirrel, an enhancement for ActiveRecord's find syntax; — amongst some other projects.

Chad (President) and Jon (CTO) co-authored a technical book titled Pro Active Record: Databases with Ruby and Rails, which explores the ins and outs of the ActiveRecord ruby library. You can buy it today at Amazon.com.
About thoughtbot, inc.
We are a small web application development consulting business, with offices in Boston, MA and New York, NY. If you're looking to find a team for your next web development project or your new web application — get in touch.
17 comments
Jump to comment form