2

I'm trying to create a scope for invoice. It's to be used in an aging view.

The invoice date is invoice.invdate.

This didn't work - it thinks DateTime is a table:

 scope :thirtydays, where("DateTime.now - DATE(invdate) < ?", 31)

This is the pg error:

missing FROM-clause entry for table "datetime"
4

1 回答 1

1

问题是您在 where 子句中将 Ruby 代码作为字符串传递,而不是使用字符串插值。

我知道您要做什么,但我认为您应该让 Rails 为您处理日期查找。

您可以使用以下内容简化代码:

class Invoice < ActiveRecord::Base
  def self.thirtydays
    where(invdate: 31.days.ago..DateTime.now)
  end
end

31.days.ago..DateTime.now将生成一个 Range 对象,该对象从 31 天前的日期开始,到今天的日期结束。Rails 将根据您的数据库平台(在本例中为 Postgresql)为您处理 SQL 日期范围调用。

它将生成类似于以下内容的 SQL 语句:

SELECT `invoices`.* FROM `invoices`  WHERE (`invoices`.`invdate` BETWEEN '2013-09-24 22:00:00' AND '2013-10-25 22:00:00')
于 2013-10-25T21:18:40.313 回答