3

How do you check in Rails3 (with or without Arel) if a date is filled in (as in, not null)? I know you can do it by using:

obj.where('PLANNED IS NOT NULL')

but is it possible without using SQL?

// SQL 
SELECT * FROM projecttasks WHERE planned IS not null

I tried:

# all tasks which have a date
tasks = Projecttask.where(:planned => !nil)

or

# all task with no planned date (sql: is null)
Projecttask.where(:planned => nil)

But that doesn't work. In general, how you can do a 'where' on NULL and NON NULL columns.

Thanks.

Roger
  • 7,535
  • 5
  • 41
  • 63
  • possible duplicate of [rail 3 where condition using NOT NULL](http://stackoverflow.com/questions/4252349/rail-3-where-condition-using-not-null) – Holger Just May 01 '12 at 19:15

3 Answers3

12

From Rails 4, there's ActiveRecord's where.not.

User.where.not(name: nil)
# SELECT * FROM users WHERE name IS NOT NULL

Until Rails 3 you'd need to use an SQL string: User.where('name IS NOT NULL')

Thomas Klemm
  • 10,678
  • 1
  • 51
  • 54
3

You can check this similar question for the answer. The answer by Ryan Bigg is what I'm guessing you are looking for.

Rails where condition using NOT NULL

Community
  • 1
  • 1
jalvarado
  • 196
  • 3
  • 1
    Thats, thanks! So you get: Projecttask.where(Projecttask.arel_table[:planned].not_eq(nil)).to_sql – Roger May 01 '12 at 18:55
0

I'm not very fluent in ActiveRecord since I mostly use Mongoid, but I think you can find your answers here : http://guides.rubyonrails.org/active_record_querying.html#conditions

I guess you have to use string conditions, as in where("planned is not null")

ksol
  • 11,835
  • 5
  • 37
  • 64
  • yeah sorry i will change my question, i wanted it without the SQL way (this is basically a bit of SQL you inject). – Roger May 01 '12 at 10:01
  • With what I read in the guide page, I don't see any mention of it, so it might not be possible. – ksol May 01 '12 at 10:04