Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I modify the query used to eager load associations

mchwalek asked in 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

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,110+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.