Share queries hard to build with plain ActiveRecord

As follow-up of What has happened to Arel, discussion happening at Where with block by brunvez · Pull Request #39445 · rails/rails · GitHub and overall movement of extending ActiveRecord API to be able to build more advanced queries I think it would be great to start collecting queries impossible or hard to build with current plain ActiveRecord API (without using sql fragments or arel directly).

Feel free to share your queries!

Few items from my personal list:

def self.only_with_royalty
  where('(revenues.royalty * COALESCE(exchange_rates.rate, 0) != 0)')
  • SELECT statement aliases
def self.with_currency
  select('accounts.currency AS account_currency')
  • Custom join table aliases are a bit clunky

Not sure whether this is something AR should be expected to be able to handle though.

  left_join("(#{SomeCustomQuery}) AS subquery ON subquery.key =")

Here are a couple I have they’re quite nasty since they’re on top of an EAV table (note: there are some variable that I have left out of scope):

attr     = EntryRecord.arel_table[field.value_attribute]
entry_id = EntryRecord.arel_table[:entry_id]
field_id = EntryRecord.arel_table[:field_id]


Here’s another, I would love go get rid of the "...#{}..."

entries.joins("left join entry_records on entry_records.entry_id = and entry_records.field_id = #{}")
       .order(field.value_attribute => direction)