MongoMapper: maintaining the sort order of an association based on a key as an array

So, I created the relationship as such:

Class Business
    include MongoMapper::Document

    key  :published_review_ids , Array         , typecast: 'BSON::ObjectId'
    many :published_reviews    , class: Review , in: :published_review_ids
end

I use publish_review_ids to maintain the sort order of my reviews, which moves them up and down in the array.

So access to Business.first.published_review_ids gives me all my ids in the correct order. Access to Business.first.published_reviews returns me an array of reviews, but sorted by default order (generation time).

Is there a way to show that this association is always sorted based on the order of the array on which it is based?

, array.first array.last Business.first.published_reviews. , : https://gist.github.com/09c9a0a23dc67f30a76d

+3
1

. - , MongoDB. , Mongo, ...

{
  "_id": { "$in" => [ObjectId('...'), ObjectId('...'), ObjectId('...')] }
}

... Mongo , , .

, .

many :published_reviews, class: Review , in: :published_review_ids, order: :published_at.desc

, :

def sorted_published_reviews
  published_review_ids.map do |id|
    # to_a will only fire a Mongo query the first time through this loop
    published_reviews.to_a.find { |review| review.id == id }
  end
end

:

first last . . (. plucky source)

/ Ruby:

my_business.published_reviews[0]
my_business.published_reviews[-1]
my_business.published_reviews.to_a.first
my_business.published_reviews.to_a.last
+2

All Articles