ruby-on-rails – 如何使用rails和mongoid通过“count”关联来查
发布时间:2020-12-16 19:10:58 所属栏目:百科 来源:网络整理
导读:有了这些型号: class Week has_many :proofsendclass Proof belongs_to :weekend 我想做的事情如下: Week.where(:proof.count.gt = 0) 仅查找具有多个证明的周数. 有一个答案似乎可以解决这个问题: Can rails scopes filter on the number of associated
有了这些型号:
class Week has_many :proofs end class Proof belongs_to :week end 我想做的事情如下: Week.where(:proof.count.gt => 0) 仅查找具有多个证明的周数. 有一个答案似乎可以解决这个问题: Can rails scopes filter on the number of associated classes for a given field 但是在这个例子中,由于ids与证明一起存储,因此在周中没有诸如proof_ids之类的属性.这不适用于例如: Week.where(:proof_ids.gt => 0) 这个查询怎么可能?在概念上很简单,但我无法弄清楚如何用mongo或mongoid做到这一点. 同样,我想按照证明的数量排序,例如: Week.desc(:proofs.size) 但这也行不通. 我确实意识到反缓存是我的两个具体问题的选项,但我也希望能够进行查询. 在此先感谢您的帮助. 解决方法
使用rails(并且没有counter_cache),您可以:
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个查询,但这远非理想. 使用范围(bug?)重复这对查询(=每次操作> 4次查询): 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 scope :with_at_least_n_proofs,-> (n = 1) { where('proofs_count >= ?',n) } scope :by_proofs_size,-> { order(proofs_count: :desc) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |