【问题标题】:rails, Query for Records that are nested with a Count() GT 0?rails,查询嵌套有 Count() GT 0 的记录?
【发布时间】:2010-10-23 19:10:35
【问题描述】:

2 个型号 书籍(has_many:章节) 章节(belongs_to:书籍)

我想显示书籍列表,但只显示带有章节的书籍。

这是我目前所拥有的:

@books = Book.find(:all,:include => :chapters)

这里的问题是书籍正在返回没有章节的书籍(0 章)

在处理这样的嵌套资源时,我怎么说 find where count > 0 for chapters?

现在我正在控制器中执行此操作,不确定这是否有问题。但我可能应该把它移到模型上?

干杯

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    将此代码添加到书:

    scope :only_with_chapters, includes(:chapters).having('COUNT(chapters.id) > 0').group('books.id')
    

    要使用它,只需运行 Book.only_with_chapters

    取决于性能使用joins,而不是includes

    使用连接将如下所示:

    scope :only_with_chapters, includes(:joins).group('books.id')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多