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! :)

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Also note, that doing this on the view (as your question sugests) is not good practice
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.
Just use (Date.today.to_time..1.week.ago) instead.
1

I think something like that should work:

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

2 Comments

I think the code has minor mistake.It should be ['curr_date <= ? AND curr_date >= ?', Date.today, 1.week.ago]
Well, the question is was it opened or closed interval :)
1

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

Comments

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)

1 Comment

The IN is not valid syntax, that should be =>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.