sixty4bit
sixty4bit

Reputation: 7956

Rails 3.2 - ActiveRecord `where` query with method called on attribute

In the console I can query my Job table like this: jobs = Job.where("created_at <= ?", Time.now)

I want to get jobs that were created this year. If I get an individual job I can use job.created_at.year but if I try to use jobs = Job.where("created_at.year = ?", 2014) I get the following error:

SQLite3::SQLException: no such column: created_at.year

I think I understand that the problem is I'm trying to mix Ruby into a SQL query but I'm not sure how to get around it. Understanding this would help me create much more powerful ActiveRecord queries.

EDIT I found that I can do this using .map like so: Job.all.map { |j| j if j.created_at.year == 2014 }. Is that the best way to do this if I want to gather a collection of jobs that requires calling a method on an attribute?

Upvotes: 0

Views: 136

Answers (1)

Surya
Surya

Reputation: 16012

Try this:

Job.where(:created_at => Time.now.beginning_of_year..Time.now.end_of_year)

Since, calling Time.now could potentially give two different years (before and after midnight on December 31) it would be better to first create a variable for the current time before it is used in a query:

current_time = Time.now
Job.where(:created_at => current_time.beginning_of_year..current_time.end_of_year)

Upvotes: 3

Related Questions