Convert SQL statement to Arel Rails query
Asked Answered
T

2

0

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?

Thais answered 26/5, 2017 at 23:44 Comment(0)
C
1

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.

Crisscross answered 27/5, 2017 at 2:49 Comment(0)
E
1

Recently I found this cool project http://www.scuttle.io/
scuttle - sql to arel converter

Euromarket answered 31/1, 2020 at 3:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.