I'm trying to search for an embedded document by its id, and return it. This is possible, but only, as far as I see, by using mongo to find the document which embeds it, and then searching that document in ruby for the embedded document I'm after. Like this:
# commenter.rb
def post
# todo: find syntax do avoid double query
if user = User.any_of({'posts.commenter_ids' => self.id}).last
user.posts.where('commenter_ids' => self.id).last
end
end
Seems simple, but I haven't found anything I like obviously on google/SO search.
Thoughts?
Right now I am including the following functionality into my embedded documents. It requires that you set the inverse_of option on the nested relationship.
You can't find a resource without the document it embeds. If you just want a relationship between the two instead of embedding it, you should use has_many instead of embeds_many http://mongoid.org/en/mongoid/docs/relations.html#has_many. You can then find the document without it's related document.
I override find method on my embedded documents using this gist: https://gist.github.com/cblavier/7889042
It's especially convenient when I want to use DelayedJob to delay embedded document methods (because DJ worker will use find(id) to deserialize the job)
See also Does querying Mongoid embedded documents hit the database server after loading a parent document