get counter nested model mongoid

44 views
Skip to first unread message

Maria Serrano Cáceres

unread,
Nov 5, 2012, 1:32:09 PM11/5/12
to mon...@googlegroups.com
2 models:

Class User
include Mongoid::Document
has_many :reports
end

Class Report
include Mongoid::Document
belongs_to :user
end

I need a query to get all users have 6 or more reports, something like:.

Users.where(reports.count > 5)

How can I do it?

Thank you very much!

Durran Jordan

unread,
Nov 8, 2012, 2:59:00 AM11/8/12
to mon...@googlegroups.com
This query is not possible since MongoDB does not have joins. You would need to store a "counter cache" for reports on the User in order to do so. A quick and dirty example:

class User
  include Mongoid::Document
  field :reports_count, type: Integer
  has_many :reports
end

class Report

  include Mongoid::Document
  belongs_to :user

  after_create do |doc|
    doc.user.inc(:reports_count, 1)
  end

  after_destroy do |doc|
    doc.user.inc(:reports_count, -1)
  end
end

2012/11/5 Maria Serrano Cáceres <maserran...@gmail.com>

Maria Serrano Cáceres

unread,
Nov 11, 2012, 11:19:40 AM11/11/12
to mon...@googlegroups.com
Thank you Durrand. Is valid for this example instead use this code use this gem https://github.com/jah2488/mongoid-magic-counter-cache

Thank you very much again Durrand!.
Reply all
Reply to author
Forward
0 new messages