mongoid/mongoid — Issue #1518: Dirty tracking is broken for Array fields
Author: ssimeonov
Created: 2011-12-22 05:46:38+00:00
State: open

In the case of a simple model with an Array field, it is very difficult to make Mongoid realize that the contents of the Array or the Array itself have changed.

```ruby
class QueryCache
include Mongoid::Document

STATUSES = {:new => 'NEW', :processed => 'PROCESSED'}

field :status, :type => String, :default => STATUSES[:new]
field :type, :type => String
field :query, :type => String
field :results, :type => Array, default: []
attr_accessible :query, :type, :results
end

```

Given the simple model above, it seems that hardly any combination of merge/clone/dup can get Mongoid to believe that the results array has changed.

```ruby
ruby-1.9.2-p290 :091 > qc.reload
=> #1, "status"=>"NEW"}]>
ruby-1.9.2-p290 :092 > qc.results[0]['status'] = "ACTIVE"
=> "ACTIVE"
ruby-1.9.2-p290 :093 > qc.changes
=> {"results"=>nil}
ruby-1.9.2-p290 :094 > qc.write_attribute(:results, qc.results.clone)
=> [{"id"=>1, "status"=>"ACTIVE"}]
ruby-1.9.2-p290 :095 > qc.changes
=> {"results"=>nil}
ruby-1.9.2-p290 :102 > qc.results = qc.results.map { |result| result['status'] = 'ACTIVE'; result.clone }
=> [{"id"=>1, "status"=>"ACTIVE"}]
ruby-1.9.2-p290 :103 > qc.changes => {"results"=>nil}
```

What's a good way to tell Mongoid that there are, in fact, changes that need to be persisted from the Array?

In this particular case, we really don't want to have to go to embedded documents...