ruby-on-rails - MongoMapper:维护基于键作为数组的关联的排序顺序

标签 ruby-on-rails mongodb mongomapper

所以我创建了这样的关系:

Class Business
    include MongoMapper::Document

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

我使用 published_review_ids 来维护我的评论的排序顺序,这使它们在数组中上下移动。

因此,访问 Business.first.published_review_ids 会以正确的顺序为我提供所有 ID。访问 Business.first.published_reviews 会带回一系列评论,但按默认顺序(生成时间)排序。

有没有办法让我告诉这个关联始终根据它所基于的数组的顺序进行排序?

附带说明一下,array.first 和 array.last 在返回的 Business.first.published_reviews 数组上似乎无法正常运行。这是一个显示一些行为示例的要点:https://gist.github.com/09c9a0a23dc67f30a76d

最佳答案

没有。由于 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

在你旁边:

直接在关联上调用firstlast 会触发查询。如果没有排序顺序,您将不会得到任何不同的东西。 ( see the 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

关于ruby-on-rails - MongoMapper:维护基于键作为数组的关联的排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10438881/

相关文章:

mongodb - 原则 ODM 和无模式设计

ruby-on-rails - current_user 如何在 devise rails 中工作

javascript - 在 Rails View 中发出 Javascript Loop 请求

mysql - 将 Phusion Passenger 从 3.0.11 更新到 4.0.10 会导致 ActiveRecord::StatementInvalid 在查询期间丢失与 MySQL 服务器的连接

mongodb - MongoMapper 接近 maxDistance - Mongo::OperationFailure:地理值必须是数字:

ruby-on-rails - MongoMapper 和迁移

ruby-on-rails - PDFTK 替代方案

java - MongoDB 的 Spring 数据

javascript - Meteor:部署到自己的服务器

regex - Mongodb - 子文档键的正则表达式匹配