Alex Rivera | Logout

How can I find records by "count" of association using rails and mongoid?

Asked 2011-11-22T07:46:33.773
9

With these models:

class Week
  has_many :proofs
end
class Proof
  belongs_to :week
end

I want to do something like:

Week.where(:proof.count.gt => 0)

To find only weeks that have multiple proofs.

There is one answer that seems to address this:

Can rails scopes filter on the number of associated classes for a given field

But in this example, there is no such attribute as proof_ids in Week since the ids are stored with the proofs. This does not work for example:

Week.where(:proof_ids.gt => 0)

How is this query possible? Conceptually simple but I can't figure out how to do this with mongo or mongoid.

Similarly, I'd like to order by the number of proofs for example like:

Week.desc(:proofs.size)

But this also does not work.

I do realize that a counter-cache is an option to both my specific questions but I'd also like to be able to do the query.

Thanks in advance for any help.

Edit
Report

1 Answer

4

I don't know if this is the best solution, as it maps it through a array, but this does the job: (the other solutions mentioned here gives me exceptions)

class Week < ActiveRecord::Base

  scope :has_proofs, -> { any_in(:_id => includes(:proofs).select{ |w| w.proofs.size > 0 }.map{ |r| r.id }) }

end
answered 2012-05-02T21:35:40.543

Your Answer