我有三节课
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
每当用户创建一个新的注释时,我想将其内容与用户最近的注释进行比较。以下是获取用户最新评论的代码:
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
上面的代码给了我结果,但是所采用的方法并不有效,因为我必须遍历用户已发出命令的所有帖子才能找到最新的评论。如果有的话,有谁能为我提供一个更有效的解决方案吗?
简单地说,难道没有任何方法可以让我得到这个用户的所有评论吗?
最佳答案
这将获取最新用户的评论:
Post.where("comments.user_id" => user.id).order_by(:'comments.updated_at'.desc).limit(1).only(:comments).first