Created
August 30, 2012 10:19
-
-
Save yannski/3525621 to your computer and use it in GitHub Desktop.
order results from a mongoid relations according to how they are stored in the relationship array of ids
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # place this file in your initializers directory to have a nice to_ordered_a method to be able to retrieve an array ordered according to the order of the *_ids source. | |
| # why doing this ? Because MongoDB allows to store array of objects. An array is not only a nice structure to store ids, it also implies that the ids are stored in a certain order. By default when you call relations in mongoid, the objects are returned in some order (certainly defined by the order of creation), not the order stores in your target array of ids. | |
| module Mongoid #:nodoc: | |
| module Relations #:nodoc: | |
| class Many | |
| def to_ordered_a | |
| original_array_ids = base.send metadata.key.to_sym | |
| original_array_indexes = Hash[original_array_ids.each_with_index.to_a] | |
| target.sort_by{ |s| original_array_indexes[s.id] } | |
| end | |
| end | |
| end | |
| end | |
| module Mongoid #:nodoc: | |
| module Relations #:nodoc: | |
| module Targets | |
| class Enumerable | |
| def to_ordered_a | |
| original_array_ids = base.send metadata.key.to_sym | |
| original_array_indexes = Hash[original_array_ids.each_with_index.to_a] | |
| target.sort_by{ |s| original_array_indexes[s.id] } | |
| end | |
| end | |
| end | |
| end | |
| end | |
| module Mongoid #:nodoc: | |
| class Criteria | |
| def to_ordered_a | |
| original_array_ids = selector[:_id]["$in"] | |
| original_array_indexes = Hash[original_array_ids.each_with_index.to_a] | |
| entries.sort_by{ |s| original_array_indexes[s.id] } | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment