ruby 如何为一个单数where子句编写一个OR查询,而不影响其余的查询?

ryoqjall  于 2023-05-28  发布在  Ruby
关注(0)|答案(2)|浏览(115)

我想写一个在where子句中使用OR语句的查询,但只有一个where子句:
以这个查询为例:

Job
      .joins(:quote)
      .joins(:revisions)
      .where.not(revisions: {approved_date: nil})
      .where(billed_date: nil)
      .where(art_billed_date: nil)
      .where.not(quote: {approval_date: nil})
      .or(Job.where(company_id: [companies_to_display]))

最后两个链条出了问题

.where.not(quote: {approval_date: nil})
      .or(Job.where(company_id: [companies_to_display]))

它们应该一起使用,并且相互依赖。我想要的是如果报价.approval_date为NIL,则仅查找要显示的公司
我如何使用Rails 7使用OR来实现这一点?

bnl4lu3b

bnl4lu3b1#

Job
      .left_joins(:quote)
      .left_joins(:revisions)
      .where.not(revisions: {approved_date: nil})
      .where(billed_date: nil)
      .where(art_billed_date: nil)
      .where.not(quote: {approval_date: nil})
      .or(Job.where(company_id: [companies_to_display]))
      .distinct

我觉得这个可以。你需要所有的作业-甚至那些没有引号的作业(left_join),然后限定结果为not(quote:{批准日期:nil})或company_id:[companies_to_display].

oyt4ldly

oyt4ldly2#

我可以使用.scoping方法解决这个问题。

Job
    .simple_datatable_includes
    .include_current_revision
    .joins(:quote)
    .where.not(revisions: {approved_date: nil})
    .where(billed_date: nil)
    .where(art_billed_date: nil)
    .scoping do
        Job
        .simple_datatable_includes
        .include_current_revision
        .joins(:quote)
        .where.not(quote: {approval_date: nil})
        .or(Job.where(company_id: companies_to_display))
     end

唯一的缺点是我在这里构建了三个查询而不是两个。查看重复的join/custom include语句。至于我的应用程序,它将吐出的记录永远不会变得那么大,因为它们是积极维护的,但如果有大量的记录,这将是一个问题。
任何重构建议都值得赞赏!

相关问题