Last active
August 29, 2015 14:25
-
-
Save hisapy/3df6d80c9a661d018ee4 to your computer and use it in GitHub Desktop.
Arel inside select list
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 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