demarque/mongoid-sorted-relations — pull request #1 by jhirn (2012-05-24 17:22:26+00:00)
Title: Avoid caching sorted id's, just use relation.key. 

...ting

Hi. Because ID's are cached when the model is loaded, a reload is required after pushing objects onto the model. The ID's are already cached in the model as relation.key, so it's possible to just use that. Observe this behavior:

```
1.9.2p290> a.b << b2
0.0060 => [BSON::ObjectId('4fbe68488451661ad800000d')]
1.9.2p290> a.b << b
0.0035 => [BSON::ObjectId('4fbe68468451661ad8000009')]
1.9.2p290> a.b.map(&:id)
0.0001 => [BSON::ObjectId('4fbe68468451661ad8000009'), BSON::ObjectId('4fbe68488451661ad800000d')]
1.9.2p290> a.sorted_b.map(&:id)
0.0004 => [BSON::ObjectId('4fbe68468451661ad8000009'), BSON::ObjectId('4fbe68488451661ad800000d')]
1.9.2p290> a.reload
1.9.2p290> a.sorted_b.map(&:id)
0.0019 => [BSON::ObjectId('4fbe68488451661ad800000d'), BSON::ObjectId('4fbe68468451661ad8000009')]
```

This commit fixes that, but you still have issue of the documents being cached after calling a.sorted_b. So this still is an issue:

```
1.9.2p290> a.sorted_b.map(&:id)
0.0002 => [BSON::ObjectId('4fbe68488451661ad800000d'), BSON::ObjectId('4fbe68468451661ad8000009')]
1.9.2p290> a.sorted_b << o3
0.0021 => [BSON::ObjectId('4fbe6a158451661ad8000011')]
1.9.2p290> a.sorted_b.map(&:id)
0.0001 => [BSON::ObjectId('4fbe68488451661ad800000d'), BSON::ObjectId('4fbe68468451661ad8000009')]
```

I understand a desire for caching here and would like to discuss the need for it vs making it optional, but this pull request can be merged in regardless to eliminate the unnecessary cache object. I can open a separate issue for the latter.