【问题标题】:Rails 3 - How do I join on a table and filter for last X days?Rails 3 - 如何加入表格并过滤过去 X 天?
【发布时间】:2012-02-20 23:35:44
【问题描述】:

我的客户有很多交易。我想选择过去 30 天内没有任何交易的所有客户(交易有一个 transaction_date)并显示客户的姓名和最后交易日期。

如何在 Rails 中进行此查询?

【问题讨论】:

    标签: ruby-on-rails activerecord join has-many


    【解决方案1】:

    在您的交易模型中:

    scope :trans_order => (:order => "transaction date ASC")
    

    在你的控制器中

    @inactive_clients = 
    Client(:include => :transactions).where
    ("max(transaction_date) < ? AND transaction_date IS NOT NULL", 
    Time.now - 30.days)
    

    那么在你看来:

    @inactive_clients .each |client|
      = client.name
      = client.transactions.trans_order.last.transaction_date
    end
    

    【讨论】:

    • 我不确定我是否理解... 我正在寻找在过去 30 天内没有任何交易的客户。交易将始终有一个 transaction_date(它不能为空)。
    • 在您要报告的 30 天期限之前是否会有交易?我认为 q 没有说清楚。
    • 也许吧。如果他们从未进行过交易,则可以不返回。如果他们的最后一笔交易是 29 天前,我不希望它被退回。如果最后一笔交易是 31 天前,我希望它在列表中。基本上是想显示一个以前付款但一个多月没有付款的客户列表。
    【解决方案2】:
    @client_transactions = Transaction.includes(:client).where('transaction_date < ?', 30.days.ago).group(:client_id)
    @client_transactions.each do |client_transaction| 
      puts "client is #{client_transaction.client.name}"
    end
    

    【讨论】:

      【解决方案3】:

      我会使用类似的不存在子句

      @clients = Client.where("not exists (select 'x' from 
          transactions where transactions.client_id = clients.id 
          and transaction_date > ?)", 
        30.days.ago)
      

      【讨论】:

        猜你喜欢
        • 2017-03-04
        • 2012-04-03
        • 2022-06-10
        • 2020-09-28
        • 2011-03-05
        • 1970-01-01
        • 2016-06-28
        • 2021-05-20
        • 1970-01-01
        相关资源
        最近更新 更多