i would like to translate this query to an active record statement to get things done in a more rails way although it could be executed as it is with ActiveRecord::Base.connection.execute
have been struggling to achieve it, any help on this will be much appreciated!
"select distinct on (papers.id) boxes.created_at, boxes.id from papers left join boxes on paper.id = boxes.id order by paper.id, boxes.created_at DESC;"
CodePudding user response:
distinct on
is not supported with a dedicated method in ActiveRecord, therefore you have to be more verbose:
Box
.select('select distinct on (papers.id) boxes.created_at, boxes.id')
.joins(:paper)
.order('paper.id, boxes.created_at DESC')
Box
and joins(:paper)
of course only works when you have your ActiveRecord models and associations properly set up.