Check Rails scope for nil

I have an expense table. It has an invoice_id column.

I would like 2 areas - one for invoiced and one for unbilled. I thought I could just check if invoice_id is there.

scope :notbilled, where(:invoice_id == nil) scope :billed, where(:invoice_id != nil) 

But that does not work.

Any ideas?

Thanks!

+7
source share
2 answers

For the first, use the hash syntax:

 scope :notbilled, where(:invoice_id => nil) 

The second requires that you use raw sql:

 scope :billed, where('invoice_id is not null') 

You can also jump into isl for the second to avoid writing raw sql, but this is an extended topic and will end up being less readable than the original sql.

Using direct equality will not work, because these expressions are evaluated immediately and turn into their logical equivalents, because no variables are involved, therefore they will be interpreted as

 scope :notbilled, where(false) scope :billed, where(true) 
+12
source

Updated answer with Rails 4:

 scope :notbilled, where(invoice_id: nil) scope :billed, where.not(invoice_id: nil) 

This is a new feature added in ActiveRecord 4.

Docs: http://edgeguides.rubyonrails.org/active_record_querying.html (search for "NOT CONDITIONS", currently section 2.4)

+4
source

All Articles