Search code examples
ruby-on-railsactiverecord

Rails ActiveRecord - Select all objects by date, using only day, month, year, but ignoring the rest of the date's components


I have a model named Event. I want to be able to get all Events that were created at some specific date which should be something like this

Event.where(created_at: "20/01/2019".to_date)

The issue is that the created_at field also contains minutes, second, etc, which I want to ignore. I only want to compare the date by day, month and year. Is there any way I can acchieve that?


Solution

  • You can use Date#beginning_of_day and Date.end_of_day both provided by ActiveSupport core extensions.

    d = '2019-01-20'.to_date 
    Event.where(created_at:(d.beginning_of_day..d.end_of_day))
    

    This will not necessarily compare "...the date by day, month and year." but instead it will create a between clause that encompasses the entire day. If you want to use the Hash finder syntax this is probably the best way to go about it.

    You could go with

    Event.where(
      Arel::Nodes::NamedFunction.new('CAST',
         [Event.arel_table[:created_at].as('DATE')]
      ).eq(d)
    )
    

    If you really only want to compare the day, month and year.

    Option 1 will result in

     events.created_at BETWEEN '2019-01-20 00:00:00' AND '2019-01-20 23:59:59'
    

    Option 2 will result in

     CAST(events.created_at AS DATE) = '2019-01-20'