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

Ticket #11514 (new defect)

Opened 1 month ago

Last modified 1 month ago

[PATCH]Using inspect on a new object's association resets the association

Reported by: acirugeda Assigned to: core
Priority: normal Milestone: 2.x
Component: ActiveRecord Version: edge
Severity: normal Keywords: association inspect
Cc:

Description

The sequence is as follows:

* Build a new object * Add associated objects using the association's build method * Call inspect on the association * The association is reset

Attachments

inspect_on_new_object_association_does_not_reload_association.diff (1.2 kB) - added by acirugeda on 04/02/08 17:23:57.
inspect_on_new_object_association_does_not_reload_association_2.diff (1.9 kB) - added by acirugeda on 04/03/08 10:26:45.

Change History

04/02/08 17:23:15 changed by acirugeda

Ups, hit submit instead of preview, sorry.

Looking inside the inspect method you can see

reload unless loaded?

and then reload does

reset
load_target

Since using build does not set loaded (opposed to <<) the associations is reset and being a new object, nothing gets loaded.

To see it in action (with bar has_many foos):

bar = Bar.new
bar.foos.build
bar.foos.size # => 1
bar.foos.inspect # => []
bar.foos.size # => 0

The patch extends the condition to reload inside inspect to take this case into account.

04/02/08 17:23:57 changed by acirugeda

  • attachment inspect_on_new_object_association_does_not_reload_association.diff added.

04/02/08 18:53:55 changed by jramirez

+1

04/03/08 10:16:20 changed by acirugeda

Second patch with a couple of minor changes:

Removed accented letter from test (showed strange characters if seen in the site).

The condition resulting from the patch is the negation of the one in load_target, but using unless instead of if, so both are exactly the same. I factored it out to its own method

needs_to_be_loaded?

This way it's a bit more descriptive and DRY.

04/03/08 10:26:45 changed by acirugeda

  • attachment inspect_on_new_object_association_does_not_reload_association_2.diff added.

04/05/08 22:29:02 changed by fxn

I think that line in inspect is flawed. Even with a conditional there's no reason to reload anything.

You want to inspect the target in memory, loading it if it is not yet there. I think the method needs_to_be_loaded? and its proposed usage in load_target is good. But I'd write inspect

def inspect
  load_target
  @target.inspect
end

That'd be analogous to ===.

04/05/08 23:07:41 changed by fxn

Oh, in fact we could even remove that definition of inspect altogether and let it go through method_missing.