简体   繁体   中英

Convert SQL statement to Arel Rails query

So, let's get straight: I'm struggling to days do convert this SQL Statement:

select * from (
    select distinct on (program_id) editions.*, programs.* 
    from editions inner join programs on editions.program_id = programs.id 
    where programs.station_id = 1) as editionsprograms 
order by fixed desc, published_at desc, time desc 
limit 4;

to an Arel rails query. Someone has any idea about how could make an Arel query that would have the same effect of the above SQL?

You can use the from method to accomplish the tricky part of your query (selecting from a subquery). The subquery itself should be a straightforward mapping ( select , joins , where , etc). So the result would be something like this:

Edition.select('*')
.from(
  Editions.select('DISTINCT ON (program_id) editions.*, programs.*')
          .joins(:programs)
          .where(programs: { station_id: 1 })
)
.order(fixed: :desc, published_at: :desc, time: :desc)
.limit(4)

This will return Edition records, with additional data from the Program record stored on each. To avoid the weirdness of that result type, which may also just throw errors and be unable to resolve, you could either use Arel directly (similar syntax) or use .pluck on the end to pluck only the columns you actually need.

Recently I found this cool project http://www.scuttle.io/
scuttle - sql 到 arel 转换器

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