Skip to content

Instantly share code, notes, and snippets.

@ktec
Last active June 27, 2016 14:39
Show Gist options
  • Save ktec/357c217630b37b057ab252eb3e80783e to your computer and use it in GitHub Desktop.
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
# 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
@ktec
Copy link
Author

ktec commented Jun 27, 2016

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?

SELECT "things".* FROM "things" WHERE (created_at >= '18/06/2016') AND (created_at <= '18/06/2016')

Wrong. That will result in an empty collection, however

SELECT "things".* FROM "things" WHERE (created_at::DATE >= '18/06/2016') AND (created_at::DATE <= '18/06/2016')

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment