在mongoid中查询和排序嵌入文档

aas*_*ash 3 ruby mongodb mongoid

我有三节课

class Post
 include Mongoid::Document
 include Mongoid::Timestamps
 belongs_to :user, :inverse_of => nil
 embeds_many :comments, :as => :commentable
 field :content, :type => String
end

class Commment
  include Mongoid::Document
  include Mongoid::Timestamps
  belongs_to :user, :inverse_of => nil
  embedded_in :commentable, :polymoriphic => true
end

class User
  has_many :posts, :dependent => :destroy
  field :name, :type => String
end
Run Code Online (Sandbox Code Playgroud)

每当用户创建新评论时,我想将其内容与用户所做的最新评论进行比较.这是我的代码,用于获取用户的最新评论:

comments_user=[]
Post.where("comments.user_id" => user.id).
     only(:comments).
     each {|p| comments_user += p.comments.where(:user_id => user.id).to_a}
latest_comment = comments_user.sort_by{|comment| comment[:updated_at]}.reverse.first 
Run Code Online (Sandbox Code Playgroud)

上面的代码给了我结果,但所采用的方法效率不高,因为我必须遍历用户已经提交的所有帖子以找到最新的评论.如果有的话,任何人都可以为我提供更有效的解决方案吗?简单来说,我有没有办法得到这个用户的所有评论?

Hck*_*Hck 5

这应该获取最新用户的评论:

Post.where("comments.user_id" => user.id).order_by(:'comments.updated_at'.desc).limit(1).only(:comments).first
Run Code Online (Sandbox Code Playgroud)