Order by in nested includes

Hello there,

I’m encountering a strange issue. I tried to google about it but I may not be using the right wording (I am quite new at RoR).

I’m using some nested eager loading through a scope of one of my models. So I have something like this:

scope :includes_all, lambda {includes(:buggy_relation, :another_relation, an_attribute: [:first_attribute, :second_attribute])}

Where :buggy_relation is declared as something like this in the same model:

has_many :buggy_relation, -> {order(:order_index)}, class_name: 'SomeClass'

So, the point is, as long as I do not have an_attribute in my includes() statement, the SQL request looks correct and I can see the ORDER BY statement done on my SomeClass.order_index. But, as soon as I add the nested loading with an_attribute: [:first_attribute, :second_attribute], the order of the :buggy_relation is not taken into account anymore. The buggy relation is obviously loaded, but nowhere is the corresponding ORDER BY stated which leads to the order not to be respected.

If you have any hint about this…


– Martin