Get records where date.year == some_year in Rails - ruby-on-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])

Related

RAILS : how to define scope with date range from column values?

I am trying to create a named scope in which I would like to receive records which are only updated within the first week after they are created.
As you can see I receive an error message for the column name created_at.
scope :shortlived, where("updated_at < ?", (created_at+7.days))
undefined local variable or method `created_at' for #<Class:0xb184725c>
I will appreciate if you can inform me what might be the problem.
You could use something database specific. For example for MySQL:
scope :shortlived, -> { where('updated_at < created_at + interval 3 day') }
this is similar to the answers posted here. if you're using postgreSQL, you can just compare the difference with '7 days' interval
scope :shortlived, -> { where("(updated_at - created_at) < '7 days'") }

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 (...)

ActiveRecord 'where' wrong number of arguments (2 for 1) when pulling in objects with a specific date window

I'm trying to pull in an array of objects from a mongo database via AR based on both a 'publish' column and a 'start_on' date column:
#featured_events = Event.where(publish: "Featured").where("start_on >= ?", Date.today).order(:start_on).all
So I want objects where publish is set to the string "Featured" and the start_on date for the event is after today. But whenever I run any variation of this I get the error 'wrong number of arguments, (2 for 1)'. But everywhere I look confirms that
.where("start_on >= ?", Date.today)
is the correct way to do this, which requires two arguments. Could it have something to do with mongo?
Thanks so much.
Replace .where("start_on >= ?", Date.today) by .where(:start_on.gte => Date.today) and tell if it's what you are expecting.

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

Proper syntax in RoR for time in datetime comparison

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.

Resources