简体   繁体   中英

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM