Satya's blog - ActiveRecord::find() in Ruby on Rails

Jun 13 2009 00:20 ActiveRecord::find() in Ruby on Rails

When I first started with Ruby on Rails, it took me some time to figure this out. ActiveRecord's find() method will return two different kinds of objects when you call it with :first versus :all.

find(:first) returns a single object. find(:all) returns an array. If no records are found (perhaps because conditions didn't match), find(:first) returns nil, while find(:all) returns the empty array. find(:all, :limit => 1) returns an array, perhaps with a single object in it. find(:first, :limit => 1) or even :limit => 2, returns a single object (or nil).

The result of find(:first) can be checked with the nil? method, and the result of find(:all) can be checked with the nil? as well as empty? method (but nil? should return false if the find() actually was executed).

In perl terms, find(:first) always returns a scalar, find(:all) always returns a list.

Last updated: Jun 13 2009 00:21

Tag: rails