1

I am trying to compare dates for an app in rails. I have tried this link Comparing dates in rails. But this is not what I want, suppose I have a filter according to dates, then I am doing

<% jobs = @user.jobs.where(:curr_date => (Date.today))%>

Here, curr_date is a "date" attribute chosen by me.

This code works for entries which have today's date, but if I want all entries which have date between today and a week before, what should I do?

Thanx! :)

Community
  • 1
  • 1
Vatsal Singh
  • 153
  • 1
  • 2
  • 9

4 Answers4

2

You can simply use

jobs = @user.jobs.where(:curr_date => (DateTime.now..1.week.ago))

Updated to DateTime.now or you can also use Date.today.to_time otherwise there will be an error for comparing a Date and a Time

Draiken
  • 3,805
  • 2
  • 30
  • 48
  • 1
    Also note, that doing this on the view (as your question sugests) is not good practice – Draiken Jul 10 '12 at 11:34
  • thanx for replying, but I get some "bad value for range" error. Instead, I tried: `<% jobs = @user.jobs.all(:conditions =>['curr_date > ?',Date.today-7])%>` and it worked for me. :) Kindly tell me the intricacies involved, if possible. – Vatsal Singh Jul 10 '12 at 11:55
  • 1
    Just use (Date.today.to_time..1.week.ago) instead. – moritz Jul 10 '12 at 12:34
1

I think something like that should work:

<% jobs = @user.jobs.where(['curr_date < ? AND curr_date > ?', Date.today, 1.week.ago])) %>

ABrukish
  • 1,432
  • 1
  • 9
  • 9
1

comparison_date_1 <=> comparison_date_2 might be useful to to you which returns -1,1,0 accordingly and you can populate them......

vamsi
  • 93
  • 9
0

Haven't tried this in a console but I think it should work:

# You need to implement the #week_before method
@user.jobs.where(:curr_date => (Date.week_before..Date.today))

Active Record Querying - Array Conditions Check under Range conditions (2.2.2)

Kashyap
  • 4,696
  • 24
  • 26