Last active
August 29, 2015 14:05
-
-
Save simpl1g/7bf491d9ff9f6f1adc36 to your computer and use it in GitHub Desktop.
complex query in arel
This file contains 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
def accounts | |
Account.arel_table | |
end | |
def subscriptions | |
Subscription.arel_table | |
end | |
def charges | |
Charge::Base.arel_table | |
end | |
def users | |
User.arel_table | |
end | |
# Attempt to write query in Arel, it is working, but less readable | |
def arel_scope | |
Account | |
.joins(:owner) | |
.join(subscriptions, Arel::Nodes::OuterJoin).on((subscriptions[:account_id].eq(accounts[:id])).or(subscriptions[:id].eq(nil))) | |
.join(charges, Arel::Nodes::OuterJoin).on((charges[:subscription_id].eq(subscriptions[:id])).or(charges[:id].eq(nil)).and(Charge::Base.resources.where_values).and(Charge::Base.with_status_new.where_values)) | |
.group(accounts[:id], users[:balance_limit]) | |
.having("coalesce(sum(charges.amount),0) <= users.balance_limit") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment