Last active
June 27, 2016 14:39
-
-
Save ktec/357c217630b37b057ab252eb3e80783e to your computer and use it in GitHub Desktop.
When you want to filter by date, but you've only got a datetime property, this will help you cast your datetime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class Things < ApplicationRecord | |
scope :filter_after_date, -> (date) { | |
where(created_at_as_date.gteq(date)) | |
} | |
scope :filter_before_date, -> (date) { | |
where(created_at_as_date.lteq(date)) | |
} | |
def self.created_at_as_date | |
Arel::Nodes::NamedFunction.new "DATE", [ arel_table[:created_at] ] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanation:
Assuming you have some Things created at 12:00 18th June 2016, and you want to query the database and retrieve only Things created on that sunny day in June. Simples, right?
Wrong. That will result in an empty collection, however
Will return the desired result. Here we've used postgres
::date
function to cast the value to a date, thereby scraping the time and enabling the query to suck up the Things we're looking for.This gist shows an example by using ruby's Arel library how you can cast the attribute to the date type and achieve this functionality.