1

I want to order through a collections with values from an association.

Example:

I got multible associations for a Post like:

  • Comments
  • Ratings
  • Attachements

How can i order the posts through this associations like:

  • order_by most_commented
  • order_by most_rated
  • order_by most_associations ....

Thank you.

Community
  • 1
  • 1
bulleric
  • 2,077
  • 6
  • 21
  • 36

1 Answers1

1

Now i can answer this question ^^

With Mongoid version 3.1 the active record feature "counter_cache" was aviable. For example i got a post with referenced comments:

class Post
  include Mongoid::Document
  field :body, type: String

  has_many :comments                                                                                                                                                                             
end



class Comment
  include Mongoid::Document
  field :body, type: String

  belongs_to :post, counter_cache: true                                                                                                                                                                             
end

in this case every post instance got an comments_count field wich contains the number of comments are referenced in the post.

Now you can order your posts with the comments_count field. Remember that this field is only available if at least one comment is present. Or set the comments_count field explicit with an default value in your model.

bulleric
  • 2,077
  • 6
  • 21
  • 36