Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #10115 (closed defect: worksforme)

Opened 2 years ago

Last modified 2 years ago

Calling empty? on a new has_many collection built via build deletes collection contents

Reported by: sethladd Assigned to: core
Priority: normal Milestone: 1.2.6
Component: ActiveRecord Version: 1.2.3
Severity: major Keywords:
Cc:

Description

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

Change History

11/09/07 03:43:27 changed by hasmanyjosh

  • status changed from new to closed.
  • resolution set to worksforme.

Have you tried this on edge? I think it was probably fixed by [8049]. Please re-open if it's still a problem on edge.