Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying and sorting embedded document in mongoid

I have three classes

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

Whenever the user creates a new comment, I want to compare the contents of it with the latest comment that the user has made. Here is my code that fetches the latest comment by the user:

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 

The above code gives me the result but the approach taken is not efficient as I have to traverse through all the posts that the user has commmented to find the latest comment. If any, can anyone provide me a more efficient solution to this problem? Simply speaking, Isn't there any way I can get all the comments made by this user?

like image 946
aash Avatar asked Jan 27 '26 07:01

aash


1 Answers

This should fetch the latest user`s comment:

Post.where("comments.user_id" => user.id).order_by(:'comments.updated_at'.desc).limit(1).only(:comments).first
like image 63
Hck Avatar answered Jan 28 '26 21:01

Hck