How do I modify the query used to eager load associations

Hi, I have a classic hierarchical entity with single level of nesting

class Job < ApplicationRecord
  has_many :children, class_name: 'Job', foreign_key: 'parent_id'
  belongs_to :parent, optional: true, class_name: 'Job'
end

When retrieving the jobs and their children from db, they can be sorted by different columns + an user defined order. The children should also be sorted within their parents. How do I make rails eager load the children with the sorting applied?

The closest thing I found are scoped associations and specifying them in includes - the problem is that I’d need to create an association per each valid column, which could be possible with metaprogramming, but kinda ugly; it’s a shame that it’s not possible to pass params to a scoped association. I’m also ready to just preload the data manually to just go forward

Here’s an article you might find helpful. It goes over what I think you are referring to. Applying scopes dynamically based on params to filter/sort records.

If you want a real world example, this pattern is used in the Ruby For Good Human Essentials app. Here is where the filter is applied. And then depending on params, scopes are applied that sometimes perform an includes or join.