私は3つのクラスを持っています
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
上記のコードで結果が得られますが、最新のコメントを見つけるためにユーザーがコメントしたすべての投稿をトラバースする必要があるため、採用されたアプローチは効率的ではありません。もしあれば、誰でもこの問題に対するより効率的な解決策を提供できますか? 簡単に言えば、このユーザーのコメントをすべて取得する方法はありませんか?