Active Record sorting using Ruby sort function

(Crossposting note: I meanwhile posted this also here:

I have a query of the form


and I would like to have the result sorted in a particular way. The
comparision function for the sort is complex and can’t be expressed by
simply ordering ascendingly or descendingly on the fields, but depends
on a complex term based on fields from both :parents and :children.

I currently use the following approach:

ordered_result=result.to_a.sort { |a,b| my_sort_function(a,b) }

I am aware that this means that all the records have to be present in
memory. If there is an easy way to avoid this, it would be nice, but
since I can ensure (from the context of the application), that the
number of records returned from the query is always smaller than a
certain, system-wide constant (currently 250), this is not a real

However, I wonder whether my approach to convert the
ActiveRecord::Relation to an array is a good idea. Maybe there is a
better way to implement sorting?


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs