The following code exposes a weakness in empty? on a has_many collection:
<pre><code>
f = Foo.new
f.bars.build
f.bars.empty?
pp f.bars
</code></pre>
When calling the code in the exact order above, f.bars.empty? does NOT realize you've added a Bar via build, and thus will go to the database to execute a SELECT COUNT(*). This, in turn, returns zero (because nothing is saved) and effectively wipes out any records you might have added via build.
The last line will return an empty array. (this is the bug)
This is a bug, as empty? should know that a record was added via build.
Note, that if you change f.bars.empty? to f.bars.length.zero? then everything works as expected.
For more information, please see my more detailed blog post:
http://www.semergence.com/2007/11/08/rails-bug-with-has-many-collections-empty-and-build/
or if that doesn't work: http://tinyurl.com/2z364o