Skip to content

Instantly share code, notes, and snippets.

@gringocl
Created March 7, 2014 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gringocl/9405243 to your computer and use it in GitHub Desktop.
Save gringocl/9405243 to your computer and use it in GitHub Desktop.
attempt to refactor using arel_table
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