Finding records by id

Edit: This article is a bit dated, since Rails 3 prefers the where method to the find method.

Rails has a number of distinct ways to find ActiveRecord objects by id. They are:

Object.find(id)

Object.find_by_id(id)

Object.find_all_by_id(id)

How do you know which one to use? Does it matter?

I found that all 3 methods have their own unique properties, and can be used when you’re looking for specific types of results. The differences can be expressed as follows:

1. Returning an ActiveRecord error or nil – The basic ‘find’ method throws an ActiveRecord::RecordNotFound error if you input an id that does not correspond to object. The other two methods return nil.

2. Whether multiple objects can be returned – The ‘find_by’ syntax only returns a single object. In contrast, the ‘find’ and ‘find_all_by_’ can return multiple objects. If you input multiple id’s into a find_by method, it will simply return the first result.

3. Whether objects are always returned as an array – For the ‘find_all_by’ method, the value is always returned in an array – even if the result is a single object.

In summary:

MethodResult Error or Nil? Number of Objects it can Return Always returns an array?
.find ActiveRecord error Multiple No
.find_by_ nil Single No
.find_all_by_ nil Multiple Yes, even for a single object.

 

Is it pronounced ‘S-Q-L’ or ‘Sequel’?

There’s really no definitive answer to this one. But the next time someone challenges your pronunciation of ‘SQL’, you can at least back up your choice with some cold hard facts.

The SQL database standard was invented in the early 70s and was originally called ‘SEQUEL’ – an acronym for Structured English Query Language. As a result of an IP dispute with british Aircraft manufacturer Hawker Siddeley, the name was shortened to SQL – Structured Query Language. Despite the change, many people continued to use the old name ‘Sequel’, according to an e-mail from one of the two inventors of the standard obtained by this intrepid blogger. Still, the inventor suggests that the ‘official’ pronunciation is probably ‘S-Q-L’, as it is spelled in the ISO Standard.