Created
March 7, 2014 04:27
-
-
Save gringocl/9405243 to your computer and use it in GitHub Desktop.
attempt to refactor using arel_table
This file contains hidden or 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
class Event < ActiveRecord::Base | |
#Existing scopes | |
scope :day, lambda {|day| where(" DATE(starts_at) = '#{day}%' | |
OR DATE(ends_at) = '#{day}%' | |
OR DATE('#{day}') BETWEEN DATE(starts_at) AND DATE(ends_at)") } | |
scope :between, lambda {|range_start, range_end| where(" DATE(starts_at) BETWEEN DATE('#{range_start}') AND DATE('#{range_end}') | |
OR DATE(ends_at) BETWEEN DATE('#{range_start}') AND DATE('#{range_end}') | |
OR ( DATE('#{range_start}') BETWEEN DATE(starts_at) AND DATE(ends_at) | |
AND DATE('#{range_end}') BETWEEN DATE(starts_at) AND DATE(ends_at) ) ")} | |
# Use Arel to compose SQL queries | |
def table | |
Event.arel_table | |
end | |
def starts(date) | |
table[:starts_at].eq(date) | |
end | |
def ends(date) | |
table[:ends_at].eq(date) | |
end | |
def day(date) | |
where(starts(date).or(ends(date)).or("DATE('#{date}') BETWEEN DATE(starts_at) AND DATE(ends_at)")) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment