【问题标题】:Get the highest days after due date in single query在单个查询中获取截止日期后的最高天数
【发布时间】:2020-10-29 15:39:40
【问题描述】:

在 Rails 6 应用程序中,我有一个 Invoice 表。客户有很多发票,发票属于客户,在发票表中,我有字段到期日期。

我需要获取发票到期日期之后的最高天数。

要从客户那里获取发票详细信息,我使用以下范围

scope :days_past_due_date, -> { where('invoice_status NOT IN (?) and due_amount > ? and due_date < ?',
[Invoice.invoice_statuses['voided'], Invoice.invoice_statuses['deleted'], Invoice.invoice_statuses["paid"]],
0.0, Date.today)}

所以我的代码是customer.invoices.days_past_due_date,这将在过滤到期日期和发票状态过滤器的数组中获取客户的发票。

有多个发票我需要通过天数计算找到在到期日中具有最高天数的发票的天数。

所以如果到期日期是 10 月 28 日,而今天是 10 月 31 日,那么到期日期会超过 3 天。

我需要获取超过发票到期日期的最多天数。

【问题讨论】:

  • 您可以指定数据库以获得更好的分辨率

标签: ruby-on-rails date activerecord


【解决方案1】:

使用 sql GROUP BY,rails .group()

Invoice.group(:customer_id).pluck(:customer_id, Invoice.arel_table[:due_date].minimum)

这将为您提供每个 customer_id 的最早到期日期。用 ruby​​ 完成剩下的工作应该足够了,或者您可以在数据库中使用稍微复杂的查询来完成。

Invoice.group(:customer_id).pluck(:customer_id, (Arel::Nodes.build_quoted(Date.today) - Invoice.arel_table[:due_date]).maximum)

这将获得每个 customer_id 的最长逾期天数。如果您只想考虑与您的范围相匹配的发票,只需在此处添加该范围即可。

Invoice.days_past_due_date.group(:customer_id).pluck(:customer_id, (Arel::Nodes.build_quoted(Date.today) - Invoice.arel_table[:due_date]).maximum)

【讨论】:

  • I got NoMethodError: undefined method `[]' for #<0x0000556a367a4f90>
【解决方案2】:

试试这个(Postgres)

这将在结果中添加一个 overdue_by Integer 列(天数)
你可以像User.first.invoices.days_past_due_date.first.overdue_by一样访问它

scope :days_past_due_date, -> { 
  select(Arel.sql %(invoices.*, CURRENT_DATE - due_date::DATE overdue_by))
  .where('invoice_status NOT IN (?) and due_amount > ? and due_date < ?',
    [Invoice.invoice_statuses['voided'], Invoice.invoice_statuses['deleted'], Invoice.invoice_statuses["paid"]], 0.0, Date.today
  )
}

【讨论】:

    猜你喜欢
    • 2017-07-30
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 2012-12-04
    • 2021-06-07
    相关资源
    最近更新 更多