This project is archived and is in readonly mode.
Heisenberg principal in ActiveRecord::Relation: observing relation changes it
-
fearless_fool
- Assigned user set to Aaron Patterson
Assigning this to Aaron, since he appears to be the relationship maven. If I'm violating lighthouse etiquette by assigning the ticket, please excuse me - I'm not sure of the process.
-
Samuel Kadolph
- Assigned user cleared.
- Tag cleared.
For future reference, misusing a physics term isn't helpful.
This is simply because the results of the relation are being cached and currently models created with
createare not added into the relation's cache.ruby-1.9.2-p0 > r = Widget.scoped => [#<Widget id: 1>] ruby-1.9.2-p0 > r => [#<Widget id: 1>] ruby-1.9.2-p0 > r.create => #<Widget id: 2> ruby-1.9.2-p0 > r => [#<Widget id: 1>]Calling
reloadon the relation proves this.ruby-1.9.2-p0 > r.reload => [#<Widget id: 1,>, #<Widget id: 2>] -
fearless_fool
@SK:
The Heisenberg reference was intended to enliven your day, even if not totally accurate. But -- absent any documentation about how relations are cached -- one would agree that having a relation change its state merely by observing it is kind of astonishing.
So, to make sure I understand, what was happening in the OP was that in the working example, relation1 was NOT being cached because nothing had forced its evaluation. In the broken example, relation1 was getting cached in its empty state and not getting reloaded after the create, so it appeared to be empty.
I can live with that if it's documented somewhere. If not, please (please) point me to the appropriate section on relations and I'd be happy to contribute to improving them.
- ff
