Comparison of datetime in where condition - ruby-on-rails

I need to add a date comparison in a query.
The field is column delivery_date timestamp without time zone
The condition should be delivery_date <= today.
I have tried :
"delivery_date < ?", Date.today
delivery_date.lt(Date.today)
"delivery_date" <= time.now [Error : NameError - undefined local variable or method `time' for ]
"delivery_date" <= Time.now [Error : ArgumentError - comparison of String with DateTime failed: ]
but I am getting different errors with all.
Here is the query where I need to add my condition :
datas: tab.project
.active
.where("delivery_date" <= date.today, step_id: Step::OPENED, test: {typess: type})
.joins(:test, :account)
.group(:'account.name')
.order('count(tab.id) DESC')
.count(:id)
Any idea how it should be done?

Try:
tab.project.active.where("delivery_date <= ?", Date.today)
or
tab.project.active.where("delivery_date <= :date", date: Date.today)
In both cases we use Date.today that returns (suprisingly :-) ) the date of today. We use two ways of adding param to a query -
array condition where ? is replaced by next where arguments (in this case the Date.today)
placeholder condition where a symbol is replaced by a hash value for this symbol (date: Date.today)

Related

Select all objects from model that respond true to the Model method

Let's say that I have a Model called Game.
That model have two fields, start_date (timestamp) and time_limit (integer)
I want to select all objects, that will return true to following statement:
start_date + time_limit.minutes > Time.now
I managed to get all objects where start_date is greater than time now, but that's not what I exactly wanted.
Game.where(["start_date > ?", Time.now])
How should I do it?
PostgreSQL
Game.where("start_date > now() - time_limit * interval '1 MINUTE'")
As start_date + time_limit.minutes > Time.now this is a simple inequation you can also write the same as: start_date > Time.now - time_limit.minutes
So your query should be:
Game.where(["start_date > ?", Time.now - time_limit.minutes])
✌️

Finding records between date range

I'm trying to find records whose start and end date range over a particular date. Date is random and :start_date and :end_date are attributes of the prices entity.
date = Time.now
record_i_want = Price.where(date => :start_date .. :end_date)
Thank you.
You can simply do
Price.where(:date => start_date..end_date)
This will result in the following SQL( for start and end dates - '2014-03-27', '2014-03-28')
SELECT `prices`.* FROM `prices` WHERE (`prices`.`date` BETWEEN '2014-03-27' AND '2014-03-28')
EDIT:
Realized that this is the query you are looking for. Thanks, Coenwulf for pointing it out
Price.where(['start_date < ? AND end_date > ?', date, date])
You want to select rows where your date is greater than the start_date and less than the end_date. You can specify the appropriate SQL where clause parameterized in your call to where like so:
Price.where([":date >= start_date AND :date <= end_date", {date: Date.today})
That will give you all the prices that match. If you know you'll get only one you can get it by calling first.
Price.where([":date >= start_date AND :date <= end_date", {date: Date.today}).first
Make any appropriate adjustment to the >= and <= if you want to exclude the start_date and/or the end_date from the results. If for example the Price is valid starting on the start_date but isn't valid through the end_date you can change the clause to:
":date >= start_date AND :date < end_date"
This should work:
def get_record_by_date(date)
Price.where([start_date.to_i < date.to_i] && [end_date.to_i > date.to_i])
end

Issue counting using conditional datetime

I'm trying to count all my policies that are'n expired >= that today
date_end >= TODAY
Here is my table
|policies|
|id| |num| |date_ini| |date_end|
1 12484 2013-04-01 2014-05-01
2 41511 2012-04-01 2013-05-01
3 14441 2013-05-01 2014-06-01
There are 2 values that aren't expired
Here is my controller
#policies =Policy.count(:conditions =>['date_end >= Date.now'])
I tried
#policies =Policy.count(:conditions =>['date_end >= Date.today'])
And also
#policies =Policy.count(:conditions =>['date_end >= curtime()'])
Please somebody can help me?
I will really appreciate help
It's not working because Date.today is inside a String, so it isn't being evaluated as an actual Date. You probably also want to use Date.current instead, to take the configured time zone into account.
Try this instead:
#policies = Policy.count( :conditions => ['date_end >= ?', Date.current] )
If date_end is stored as a DATE type of attribute, you can do this:
Policy.where("date_end >= ?", Date.today).count
or if it's stored as a string, just convert the Date.today to a string:
Policy.where("date_end >= ?", Date.today.to_s).count
The problem is that when you call out Date.today, you are returning the format "Fri, 15 Nov 2013" which will not compare to "2014-04-02". To get them in the same format, use
Date.today.to_s

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!
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}
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);
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])

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])

Resources