Sorting
Sorting usually happens with no developer intervention, instead handled automatically by an Adapter. To customize:
sort do |scope, attribute, direction|
scope.order(attribute => direction)
end
A real-life example might be sorting on a different table. Let’s say an
Employee has many Positions, and title
lives in the positions
table:
sort do |scope, attribute, direction|
if attribute == :title
scope.joins(:positions).order("positions.title #{direction}")
else
scope.order(attribute => direction)
end
end
Note: the same
sort
proc will fire for every sort parameter supplied in the request. In other words, yes - you can multisort!
Sorting Relationships
Prefix the sort parameter with the relevant JSONAPI Type like so:
/blogs?include=posts&sort=posts.title