Monday, February 21, 2011

Rails ActiveRecord date between

I need to query comments made in one day. The field is part of the standard timestamps, is created_at. The selected date is coming from a date_select. How can I use ActiveRecord to do that?

I need somthing like:

"SELECT * FROM comments WHERE created_at BETWEEN '2010-02-03 00:00:00' AND '2010-02-03 23:59:59'"
From stackoverflow
  • This code should work for you:

    Comment.find(:all, :conditions => {:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day})
    

    For more info have a look at Time calculations

    rtacconi : Ok but from the form I get this: {"written_at(4i)"=>"18", "written_at(5i)"=>"56", "content"=>"rrrrrr", "written_at(1i)"=>"2010", "written_at(2i)"=>"5", "written_at(3i)"=>"4"} How can I build an object to use beginning_of_day?
    baijiu : Please add the code of the form in your question...
    rtacconi : This is what I need: http://purab.wordpress.com/2009/06/16/deconstructing-date_select-in-rails/
  • If you only want to get one day it would be easier this way:

    Comment.all(:conditions => ["date(created_at) = ?", some_date])
    

0 comments:

Post a Comment