Proper syntax in RoR for time in datetime comparison - ruby-on-rails

I am trying to attribute the time param with .to_date to generate the proper comparison
Organization.find(1140).events.all(:conditions => ["time < ?", Time.now.beginning_of_day]).blank?
How would I do that? I tried this :
Organization.find(1140).events.all(:conditions => [time.to_date < ?, Time.now.beginning_of_day]).blank?
And that's a big fail :D

You can do something like this:
Organization.find(1140).events.all(:conditions => ["DATE(time) < ?", Date.today]).blank?
DATE() is a mysql function to parse the given value to Date format. And if you want to compare dates you should use Date.today instead of Time.now.beginning_of_day, it's much shorter and more readable.

Related

Search records between two dates - Ruby on Rails

I am trying to create a search that returns records between two dates (today and a future date).
I can get it to return several records no problem if I use the following code in my model (film.rb):
def self.date_search(search_string)
self.where("release_date >= ?", search_string )
However, when I try something like the following, I receive syntax errors:
def self.date_search(search_string)
date = Date.today
self.where("release_date = created_at > date.strftime("%F") AND created_at < ? ", search_string )
I am still very new to Ruby so any help sorting out my syntax and code would be much appreciated.
Try:
def self.date_search(search_string)
self.where({release_date: Time.now..search_string})
end
This will give you entries where release_date is between the current time and the search_string (inclusive of the search string since you use two dots(..), it would be exclusive of the search string if you used three dots (...)

comparison Operators in thinking Sphinix

I have a model with attributes start_date and end_date. I have search form where user will put the date and I should get a data from the model if date is in between start_date and end_date.
how should I create a query with thinking sphinx.
You will need to do something like the following:
Add both start_date and end_date as attributes (not fields) to your model's Sphinx index.
Translate form params into a date or time value
Use range filters to limit search queries.
I've opted for very large windows of time, but essentially this ensures the given date is equal to or larger than the start date and less than or equal to the end date.
beginning, ending = Time.utc(1970), Time.utc(2030)
Model.search :with => {
:start_date => beginning..date_from_params,
:end_date => date_from_params..ending
}

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

Selecting table entries where a given date is between the :start date and :end date

I have an object that has a start date and an end date, in order to represent the time that the object is valid.
Given a date, is there a way to only select those objects that have valid ranges that contain the date?
I tried fiddling with between, but couldn't get the syntax right.
Thanks!
This is often implemented using a named scope that does the appropriate restriction that identifies which records are visible at the current point in time:
class MyRecord < ActiveRecord::Base
named_scope :visible,
:conditions => 'visible_from<=UTC_TIMESTAMP() AND visible_to>=UTC_TIMESTAMP'
end
This can be altered to use place-holders for more arbitrary dates:
class MyRecord < ActiveRecord::Base
named_scope :visible_at, lambda { |date| {
:conditions => [
'visible_from<=? AND visible_to>=?',
date, date
]
}}
end
Presumably your dates are stored as UTC, as it is a considerable nuisance to convert from one local-time to another for the purposes of display.
You can select all visible models like this:
#records = MyRecord.visible.all
#records = MyRecord.visible_at(2.weeks.from_now)
If you were doing this for "given_date".
select *
from table
where start_date <= given_date
and end_date >= given_date
This is how you'd do it using active record.
Foo.find(:all, :conditions => ['valid_from <= ? and valid_to >= ?', valid_date, valid_date])

Resources