Ruby on Rails - Date Comparison - ruby-on-rails

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

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

I think something like that should work:
<% jobs = #user.jobs.where(['curr_date < ? AND curr_date > ?', Date.today, 1.week.ago])) %>

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

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)

Related

Ruby on Rails querying over dateTime

I need to rewrite some DB query so my Rails app can run on Heroku. In one query I need to fetch all entries which are not older then one day. I tried it like this=>
Sendnotifications.where(:actionID => actionID.to_s,
:time => ['? >= time => ?', DateTime.now,DateTime.now-1]).all.count
But this does not work, I guess because of a wrong syntax. So the question is how can I solve this query problem?
Thanks :D
No need to specify two boundaries, one will be more than enough (this way the code will look cleaner):
Sendnotifications.where('time > ?', DateTime.now - 1) #chain all your other methods
Sendnotifications.where(actionID: actionID.to_s)
.where("time between ? and ?", DateTime.now, DateTime.now-1)
.count

How to query for all records created today (midnight UTC..Now)

I'm trying to create a created_at query range that will capture all records created from midnight UTC (db default) to now. In the past I've been able to query for time ranges with:
created_at => (24.hours.ago..Time.now)
But adjusting the above for the new use case does not work:
created_at => (Date.today..Time.now)
Any suggestions on how I can update the created_at range to be all records today / not in the last 24 hours?
Thanks
created_at => (DateTime.now.at_beginning_of_day.utc..Time.now.utc)
I think, you can try for below line as well.
ModelName.all :condition => ["DATE(created_at) = DATE(?)", Time.now]
OR In Rails 3
Model.where "DATE(created_at) = DATE(?)", Time.now
Cheers!
I think time zone should be considered.
where(:created_at => Time.zone.now.beginning_of_day.utc..Time.zone.now.end_of_day.utc)
And Rails will change time to utc time automatically, so the following is also ok.
where(:created_at => Time.now.beginning_of_day..Time.now.end_of_day)
Since Rails5.1, A new method Date#all_day was introduced, which returns a range of a day.
Instead of:
where(created_at: Date.today.beginning_of_day..Date.today.end_of_day)
An elegant way is:
where(created_at: Date.today.all_day)
Date.today.beginning_of_day.utc..Date.today.end_of_day.utc

rails date ranges for same date

Query below works fine when user selects different dates but when user selects same dates like 3/5/2011 and 3/5/2011 it returns nothings. How can i handle this ? If user selects same dates, i want it to find clients which are created at that date.
Client.where(:created_at => date_from..date_to)
You may need to modify your query as below to get between beginning_of_day and end_of_day
Client.where(:created_at => date_from.beginning_of_day..date_to.end_of_day)
You could create a helper method:
def date_range(from, to)
from == to ? from : from..to
end
Client.where(:created_at=>date_range(date_from,date_to))

Get records where date.year == some_year in Rails

I have a date column in my database in a Rails 3.1 app, and I want to be able to get the records where the date's year matches a specific year.
I tried where(:date.year == year) but of course I got NoMethodError: undefined method 'year' for :date:Symbol. Is it possible to do this type of query?
You can use a scope to build something like:
scope :for_year, lambda {|date| where("date >= ? and date <= ?", "#{date.year}0101", "#{date.year}1231")}
In your Model:
scope :by_year, lambda { |year| where('extract(year from created_at) = ?', year) }
In your Controller:
#courses = Course.by_year(params[:year])
Jesse gave you, I think, the idea for the actual solution, but to explain why this failed - it's because it tried to evaluate ".year" as a method on the symbol you passed it: ":date".
The word :date is just a parameter to tell "where" which value it will later use to construct the SQL query to pass to the db.
It doesn't turn into the actual date of the record. But the ".year" will evaluate as you're passing it as a parameter, before anything has been done with the ":date" symbol.
Assuming your date format is: YYYY-MM-DD HH:MM:SS
Try this:
where(Date.strptime(:date, "%Y-%m-%d %H:%M:%S").year == year)
OR
where(["YEAR(?) = ?", :date, year])

How to use datetime in the condtions of a find/count in Ruby on Rails

I'm trying to count the number of rows in a certain table by datetime.
More specifically, by a certain month, but can't find the right way to
write the conditions for it.
xxx.count(:all, :conditions=> :xxx => yyy)
I have a datetime yyy to compare with xxx, but only want to compare the year and month.
The more efficient way is like this:
range = Date.today.beginning_of_month..Date.today.end_of_month
Model.count(:conditions => {:date_field => range})
This will generate a range condition, which, if you have an index on the date_field will be very fast even for millions of rows.
I have a plugin/gem called by_star which you can install using just sudo gem install by_star if you have gemcutter.org as one of your sources.
This plugin allows you to do this:
Post.by_month("January", :year => 2009)
Which will return all records from the Post model from January 2009.
This might work.
:conditions => ["month(date_field) = ? AND year(date_field) = ?", month, year]

Resources