如何通过“计数"找到记录?使用rails和mongoid的关联? [英] How can I find records by "count" of association using rails and mongoid?
问题描述
使用这些模型:
class Week
has_many :proofs
end
class Proof
belongs_to :week
end
我想做类似的事情:
Week.where(:proof.count.gt => 0)
仅查找具有多个证明的星期.
To find only weeks that have multiple proofs.
似乎有一个答案可以解决这个问题:
There is one answer that seems to address this:
但是在本示例中,由于ID与证明一起存储,因此在Week中不存在诸如proof_ids之类的属性.例如,这不起作用:
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)
如何进行此查询?从概念上讲很简单,但我不知道如何使用mongo或mongoid做到这一点.
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)
但这也不起作用.
我确实意识到计数器缓存是我两个特定问题的一种选择,但我也希望能够进行查询.
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.
在此先感谢您的帮助.
推荐答案
有了Rails(并且没有counter_cache),您可以这样做:
With rails (and without counter_cache), you could do:
class Week < ActiveRecord::Base
has_many :proofs
def self.by_proofs_size
sort_by { |week| week.proofs.size }
end
def self.with_at_least_n_proofs(n = 1)
select { |week| week.proofs.size >= n }
end
end
尽管这些操作中的每一个都会产生2个查询,但这还是不理想的.
Even though each of those operations produces 2 queries, this is far from ideal.
使用范围(错误?)重复该对查询(每个操作==> 4个查询):
The pair of queries is repeated (=> 4 queries for each operation) with scopes (bug?):
scope :with_at_least_n_proofs, -> (n = 1) { select { |w| w.proofs.size >= n } }
scope :by_proofs_size, -> { sort_by { |w| w.proofs.size } }
理想的情况是使用counter_cache
The ideal is probably to use counter_cache
scope :with_at_least_n_proofs, -> (n = 1) { where('proofs_count >= ?', n) }
scope :by_proofs_size, -> { order(proofs_count: :desc) }
这篇关于如何通过“计数"找到记录?使用rails和mongoid的关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!