Skip to content

Instantly share code, notes, and snippets.

@mrpunkin
Created March 7, 2012 21:47
Show Gist options
  • Save mrpunkin/1996454 to your computer and use it in GitHub Desktop.
Save mrpunkin/1996454 to your computer and use it in GitHub Desktop.
Using arel to query SQL functions
dc = Arel::Nodes::NamedFunction.new "DATE", [ p[:created_at] ] ## second argument must be an array
## Sub this...
arel.project("DATE(`photos`.`created_at`)")
## For this...
arel.project(dc.to_sql)
arel.to_sql >> "SELECT DATE(`photos`.`created_at`) FROM `photos` INNER JOIN `votes` ON `photos`.`id` = `votes`.`photo_id`"
time = Arel::Nodes::NamedFunction.new "CAST", [ p[:created_at].as("TIME") ]
time.to_sql >> "CAST(`photos`.`created_at` AS TIME)"
p = Arel::Table.new("photos")
v = Arel::Table.new("votes")
## We aren't using SQL here
arel = p.join(v).on(p[:id].eq(v[:photo_id]))
## So why should we here
arel.project("DATE(`photos`.`created_at`)")
arel.to_sql >> "SELECT DATE(`photos`.`created_at`) FROM `photos` INNER JOIN `votes` ON `photos`.`id` = `votes`.`photo_id`"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment