ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button
  Rolling with Ruby on Rails, Part 2
Subject:   find vs. find_all
Date:   2006-10-13 07:35:42
From:   EgonJGF
I kept getting the error, "undefined method 'each'" when working on the results from the following code:

channels = Channel.find_by_network_id(network_id)

It turns out that the statement was returning a structure of one channel, NOT a collection containing one channel structure.

This meant that I'd get the above error if I tried to iterate through the expected "collection" of 1 or more channels. It wasn't a collection and, therefore, didn't have an 'each' method.

After looking here for the answer, I figured out that using the following code always brought back a collection, regardless of how many records matched the criteria:

channels = Channel.find_all_by_network_id(network_id)

Hope this helps someone down the road. Let me know if there's a more elegant (or acceptable) way of doing this.