Rails ActiveRecord date between
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)
I would personally created a scope to make it more readable and re-usable:
In you Comment.rb, you can define a scope:
scope :created_between, lambda {|start_date, end_date| where("created_at >= ? AND created_at <= ?", start_date, end_date )}
Then to query created between:
@comment.created_between(1.year.ago, Time.now)
Hope it helps.
Rails 5.1 introduced a new date helper method all_day
, see: https://github.com/rails/rails/pull/24930
>> Date.today.all_day
=> Wed, 26 Jul 2017 00:00:00 UTC +00:00..Wed, 26 Jul 2017 23:59:59 UTC +00:00
If you are using Rails 5.1, the query would look like:
Comment.where(created_at: @selected_date.all_day)