Gabriel
Gabriel

Reputation: 45

how to translate this PostgreSQL query into activerecord

SELECT id, (SELECT SUM(s) FROM UNNEST(invested) s) as temp from times ORDER BY temp DESC NULLS LAST;

Upvotes: 0

Views: 104

Answers (1)

pcrglennon
pcrglennon

Reputation: 457

You can pass raw SQL to #select in order to select dynamic/calculated values. Untested, but see if something like this works:

tasks = Task
  .select('id, (SELECT SUM(s) FROM UNNEST(priorities) s) AS temp_sum')
  .order(temp_sum: :desc)

# tasks.first.id => the Task ID
# tasks.first.temp_sum => the SQL-calculated value

Postgres orders nulls last by default, so the NULLS LAST isn't strictly necessary. Though of course you could keep it in if you want to be fully explicit: .order('temp_sum DESC NULLS LAST').

It's not an issue for this exact use case, since you're not passing in any user-inputted values, but just as a general warning: always be careful about SQL injection vulnerabilities when passing in raw SQL! Because Rails won't be able to perform all of its input-sanitizing magic when you just pass in raw strings.

Upvotes: 1

Related Questions