Ruby-on-rails – Rails ActiveRecord date between

rails-activerecordruby-on-railsruby-on-rails-2

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 something like:

"SELECT * FROM comments WHERE created_at BETWEEN '2010-02-03 00:00:00' AND '2010-02-03 23:59:59'"

Best Answer

Just a note that the currently accepted answer is deprecated in Rails 3. You should do this instead:

Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)

Or, if you want to or have to use pure string conditions, you can do:

Comment.where('created_at BETWEEN ? AND ?', @selected_date.beginning_of_day, @selected_date.end_of_day)