views:

9

answers:

1

In rails you can use .each do || to loop through the returned results of a query. But what if only one line is returned? or you have the possibility of 0, 1, or many? how do you handle these scenarios without throwing an error?

This situation in particular is one where i am accepting nested attributes following ryan's railcast blog (http://railscasts.com/episodes/196-nested-model-form-part-1)

I can have 1 or many nested items being returned which I then need to loop through and write an XML form.

+1  A: 

When you're looping through a set of results with #each, you don't need to worry about how many results were returned. If zero, there won't be any elements in your array to pass to the loop; if one, only one. If more, then each is passed to the loop. In each case, as long as you're just looping over an array, it doesn't matter if the array is empty, or if it has a thousand elements, the same loop code will run without an error.

By means of example, I can loop over arrays with different numbers of elements without any issue:

ree-1.8.7-2010.02 > [].each {|e| puts e }
 => []
ree-1.8.7-2010.02 > [1].each {|e| puts e }
1
 => [1]
ree-1.8.7-2010.02 > [1,2,3].each {|e| puts e }
1
2
3
 => [1, 2, 3]
Chris Heald