【问题标题】:how to order through a mongoid association如何通过 mongoid 关联订购
【发布时间】:2013-05-09 00:49:02
【问题描述】:
我想通过具有关联值的集合进行排序。
例子:
我为一个帖子获得了多重关联,例如:
我如何通过以下关联订购帖子:
- order_by most_commented
- order_by most_rated
- order_by most_associations ....
谢谢。
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-3
mongoid3
【解决方案1】:
现在我可以回答这个问题了^^
使用 Mongoid version 3.1 可以使用活动记录功能“counter_cache”。
例如,我收到了一个引用 cmets 的帖子:
class Post
include Mongoid::Document
field :body, type: String
has_many :comments
end
class Comment
include Mongoid::Document
field :body, type: String
belongs_to :post, counter_cache: true
end
在这种情况下,每个帖子实例都有一个 cmets_count 字段,其中包含帖子中引用的 cmets 数量。
现在您可以使用 cmets_count 字段对您的帖子进行排序。
请记住,此字段仅在至少存在一条评论时可用。
或者在模型中使用默认值显式设置 cmets_count 字段。