Rails 4:选择当前日期和给定的特定日期/过去天数之间的记录

时间:2016-02-03 08:37:50

标签: ruby-on-rails postgresql ruby-on-rails-4

我的Rail应用中有客户表。在客户表中,一个字段是 customer_expiry_date

我想在我的应用程序中添加一个过滤器,这意味着所有过期的客户都符合以下标准:

  1. 在一(1)天内过期。
  2. 七(7)天后到期。
  3. 在一(1)个月内过期。
  4. 我应该如何使用where子句编写查询来实现此目的?

    我当前的查询如下:

    @customers = Customer.where.not(customer_expiry_date: nil)
    

    如何根据我的要求将客户选入三个集合?

    @customers_exp_1day = ?
    @customers_exp_1week = ?
    @customers_exp_1month = ?
    

2 个答案:

答案 0 :(得分:1)

@customers_exp_1day = Customer.where("customer_expiry_date <= ?",
    Date.tomorrow)
@customers_exp_1week = Customer.where("customer_expiry_date <= ?",
    Date.today + 1.week)
@customers_exp_1month = Customer.where("customer_expiry_date <= ?", 
    Date.today + 1.month)

您的问题中有“客户”,我在这里使用“客户”,假设您的模型名称实际上是单数。

答案 1 :(得分:1)

只需在模型中编写范围:

class Customer < ActiveRecord::Base
  # your code
  scope :expired_in, -> (from_now) {
    where.not(customer_expiry_date: nil).where('customers."customer_expiry_date" >= ? AND customers."customer_expiry_date" <= ?', Time.now, Time.now + from_now)
  }
end

然后使用它:

@customers_exp_1day = Customer.expired_in(1.day)
@customers_exp_1week = Customer.expired_in(1.week)
@customers_exp_1month = Customer.expired_in(1.month)

现在它可以使用最新的更新。

相关问题