John
John

Reputation: 6612

Comparing Time.now with model dates

my Project model has 2 datetime atttributes: start_date and end_date. Now I want all projects where the current time is in between these dates. I tried something like this with the start_date to start with:

@projects = Project.where(:start_date <= Time.now)

But this returns an error:

comparison of Symbol with Time failed

Any ideas? Thanks!

Upvotes: 3

Views: 5022

Answers (3)

Veraticus
Veraticus

Reputation: 16064

Unfortunately, with a where clause comparing dates, you'll have to drop into SQL. Try something like this instead:

@projects = Project.where(['projects.start_date <= ?', Time.now])

Upvotes: 0

user229044
user229044

Reputation: 239250

You can't do this: :start_date <= Time.now. You're comparing a symbol and a date with the <= operator.

If you want to add a condition to your query, pass it as a string:

Project.where("start_date <= ?", Time.now);

Upvotes: 1

Frederick Cheung
Frederick Cheung

Reputation: 84114

Unlike some ORMs, active record doesn't augment the symbol class with methods to allow expressions other than equality to be expressed in this way. You just have to do

Project.where('start_date <= ?', Time.now)

The squeal gem adds this sort of stuff and allows you to write

Project.where{start_date < Time.now}

Upvotes: 12

Related Questions