Skip to content

Instantly share code, notes, and snippets.

@nogtini
Forked from StevenJL/common_query.rb
Created August 15, 2019 17:39
Show Gist options
  • Save nogtini/b7663667fdbd0cf1a2b3772b4da2923d to your computer and use it in GitHub Desktop.
Save nogtini/b7663667fdbd0cf1a2b3772b4da2923d to your computer and use it in GitHub Desktop.
# Under STI, find the top 10 accounts with the greatest balances
# with just one query.
top_accounts = Account.order(balance: :desc).limit(10)
# Under MTI, we need to query all accounts and sort them in memory:
top_corporate_accts = CorporateAccount.order(balance: :desc).limit(10)
top_sb_accts = SmallBusinessAccount.order(balance: :desc).limit(10)
top_personal_accts = PersonalAccount.order(balance: :desc).limit(10)
top_accounts = (top_corporate_accts + top_sb_accts + top_personal_accts).sort do |acct1, acct2|
acct1 <=> acct2
end.first(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment