Stupid Rails Tricks: Using find and find_all on ActiveRecord collections

ActiveRecord collections are enumerable, but they override Enumerable’s find and find_all methods to hit the database. But the versions on Enumerable are totally different. They feed objects to a block and return the ones for which the block returns true. Sometimes that’s what you want.

I used to convert the collection to an array so I could use the Enumerable methods, but that is far from optimal in terms of memory use. Then I figured out Enumerable has the detect and select aliases which work the same way, and work on AR collections:

# Find all the broody chickens that weigh at least 5 lbs:
Chickens.broody.find(:first, :conditions => ["weight >= ?", 5])
 
# Find all the broody chickens whose favoriate food is snails:
Chickens.broody.detect do |chicken|
  chicken.meals.map(&:food).mode == "snail"
end
 
# Instead of having to do 
Chickens.broody.to_a.find_all do |chicken|
  ...

Previous trick: Range to the end of an array

Tags: ,

One Response to “Stupid Rails Tricks: Using find and find_all on ActiveRecord collections”

  1. Erik on Rails » Blog Archive » Stupid Ruby Tricks 3: Injecting an operator Says:

    [...] Previous trick: Using find and find_all on ActiveRecord collections [...]

Leave a Reply