用于 has_many 关系中子项计数的 rails3 范围 [英] rails3 scope for count of children in has_many relationship

查看:44
本文介绍了用于 has_many 关系中子项计数的 rails3 范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图在 rails3 中做一个范围.

trying to do a scope in rails3.

:book has_many :chapters 

我想要范围 :long 返回超过 10 章的书籍.

I want scope :long to return books with > 10 chapters.

如何最好地构建此范围(不使用计数器缓存)?

How best to structure this scope (without use of counter cache) ?

谢谢!

推荐答案

这应该可以帮助您:

class Book
  scope :long, joins(:chapters).
                 select('books.id, count(chapters.id) as n_chapters').
                 group('books.id').
                 having('n_chapters > 10')
end

有帮助吗?

这篇关于用于 has_many 关系中子项计数的 rails3 范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆