Skip to content

Instantly share code, notes, and snippets.

@hisapy
Last active August 29, 2015 14:25
Show Gist options
  • Save hisapy/3df6d80c9a661d018ee4 to your computer and use it in GitHub Desktop.
Save hisapy/3df6d80c9a661d018ee4 to your computer and use it in GitHub Desktop.
Arel inside select list
class Client
has_many :sales, dependent: :restrict_with_error
# This is an example of how to use an Arel projection inside a select list.
scope :with_sales_totals, -> {
clients = arel_table
sales = Sale.arel_table
# this is will be agregated in the final query in the select list
receivables_sum = sales
.project(sales[:receivable].sum)
.where(sales[:client_id].eq(clients[:id]))
joins(sales: :sale_items)
.select(
'clients.*',
'SUM(qty*unit_price) AS sales_total',
receivables_sum.as('sales_receivable'))
.group('clients.id')
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment