views:

237

answers:

3

We have a grid control that allows a user to filter text in different fields. A number of these fields might be timestamps, like created_at and updated_at.

Now, a user can do many different types of filters, including >, <, >=, <=, etc. So, a query that comes across from the control might look like:

"created_at > 2009", or "created_at >= 2006 and created_at <= 2010".

The database doesn't recognize years as valid timestamps, nor does rails automatically convert them as such. Are there any plugins or idiomatic ways to accomplish taking a year, or better yet, portion of a timestamp, making a best guess at the meaning, and converting it into a usable database timestamp?

+3  A: 

Have a look at the following projects

For example, searchlogic supports conditions like the following one.

Post.all(:conditions => { :hour_of_created_at => 9 })
Simone Carletti
searchlogic looks mintox - I think it'll do what is needed here, though I have not implemented it yet myself.
mlambie
+2  A: 

created_at > 2009

Post.all(:conditions => ["created_at > ?", Date.new(y = 2010, m = 1, d = 1).to_s])

created_at >= 2006

Post.all(:conditions => ["created_at >= ?", Date.new(y = 2006, m = 1, d = 1).to_s])

created_at <= 2010

Post.all(:conditions => ["created_at <= ?", Date.new(y = 2010, m = 12, d = 31).to_s])

Something like this perhaps?

Barry Gallagher
+1  A: 

you can use ruby's Time class

Time.local(2010) # => Fri Jan 01 -0600 2010

or

Time.gm(2010) # => Fri Jan 01 00:00:00 UTC 2010
ErsatzRyan