ralprt
ralprt

Reputation: 21

rails 4 eager loading - order nested associations

I have 4 models

class A < ActiveRecord::Base 
  has_many :Bs
end 

class B < ActiveRecord::Base 
  belongs_to :A
  has_many :Cs
  has_many :Ds
end

class C < ActiveRecord::Base 
  belongs_to :B
end

class D < ActiveRecord::Base 
  belongs_to :B
end

I need to eager load A, and get all nested associations. So from A:

eager_load(Bs: [:Cs, :Ds]).where('id=?',id).to_a

Now I want to order B records through the eager loading. I tried to add the order through the association like this:

class A < ActiveRecord::Base 
  has_many :Bs, -> { order("id desc") }
end 

But it doesn't work. When I do something like

A.first.bs

B records are not ordered by id desc.

Could you please advice on this one?

Thanks.

Upvotes: 2

Views: 929

Answers (1)

Gaurav Tiwari
Gaurav Tiwari

Reputation: 23

I haven't tested this, but you could do this to order the Bs by id or any other field you like:

eager_load(Bs: [:Cs, :Ds]).where('id=?',id).order('Bs.id DESC')

The other option would be to setup a default scope on the model, like so:

def self.default_scope
  order(id: :desc)
end

Upvotes: 1

Related Questions