Skip to content

Instantly share code, notes, and snippets.

@shingara
Created July 9, 2010 10:17
Show Gist options
  • Save shingara/469319 to your computer and use it in GitHub Desktop.
Save shingara/469319 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
def comments
Post.where('comments.user_id' => self.id).all.select {|post|
post.comments.select{|c| c.user_id == self.id}
}.flatten.uniq
end
end
class Post
include Mongoid::Document
embeds_many :comments
end
class Comment
include Mongoid::Document
field :user_id
embedded_in :parent, :inverse_of => :comment
end
I have several users, several posts and for every post, several comments.
Every post has one user. However the user table isn't on mongodb (I could talk with you about why. But please, that's not the question here).
I'm looking forward getting all the comments for one user.
So looping through all the posts to get the comments with user_id = x.
@dmathieu
Copy link

dmathieu commented Jul 9, 2010

En fait c'est presque ça. Il me retourne tous les commentaires des posts auxquels un utilisateur a commenté.
Si un post a été commenté deux fois, une fois par l'utilisateur A et l'autre fois par l'utilisateur B

Et que je fait A.comments alors, le commentaire de B sera aussi retourné.

@shingara
Copy link
Author

shingara commented Jul 9, 2010

J'ai modifié pour que ca se rapporte plus à ton cas effectivement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment