Rails范围测试为零

Red*_*irt 7 ruby-on-rails

我有一张费用表.它有一列invoice_id.

我想要2个范围 - 一个用于计费费用,一个用于未计费.我以为我可以测试一下invoice_id是否为零.

scope :notbilled, where(:invoice_id == nil)
scope :billed, where(:invoice_id != nil)
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用.

有任何想法吗?

谢谢!

x1a*_*1a4 12

对于第一个,您需要使用哈希语法:

scope :notbilled, where(:invoice_id => nil)
Run Code Online (Sandbox Code Playgroud)

第二个要求你使用原始sql:

scope :billed, where('invoice_id is not null')
Run Code Online (Sandbox Code Playgroud)

您也可以跳转到第二个arel以避免编写原始sql,但这是一个高级主题,并且最终会比原始sql更不易读.

使用直接相等是行不通的,因为这些表达式是立即求值的,并且由于不涉及变量而被转换为它们的布尔等价物,因此它们将被解释为

scope :notbilled, where(false)
scope :billed, where(true)
Run Code Online (Sandbox Code Playgroud)