【问题标题】:Rails selecting objects with conditions on associationsRails 选择具有关联条件的对象
【发布时间】:2023-03-20 12:53:02
【问题描述】:

我有作者(作者表)和 has_many 书。课本(书表)。我如何有效地选择至少拥有一本书的作者。目前正在使用。

@authors = Author.where(:active => true).select { |author| author.books.count > 0 }

它运行良好,但运行许多查询。我怎样才能以更有效的方式做到这一点?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    你可以用 sql 来做:

     Author.where(:active => true).joins(:books).group("author_id HAVING count(books.id) > 0")
    

    【讨论】:

    • 感谢它有效,但在我的情况下,我不得不将 .group("author.id ....") 更改为 .group("author_id ....") 并且声明就像: Author.where(:active => true).joins(:books).group("author_id HAVING count(books.id) > 0")
    【解决方案2】:
    Author.where(:active => true).joins(:books).group(:id).having("count(books.id) > 0")
    

    更多更好的方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      • 2020-06-26
      相关资源
      最近更新 更多