New Discussion

Notifications

You’re not receiving notifications from this thread.

How do I modify the query used to eager load associations

0
Databases

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

Join the discussion
Create an account Log in

Learning Ruby on Rails? Join our newsletter.

We won't send you spam. Unsubscribe at any time.