1

Is there a way to pre-sort the children of a parent through ActiveRecord (Rails 3.2.13)?

So if you have a setup like this

class Parent < ActiveRecord::Base
has_many :children

[...]

class Children < ActiveRecord::Base
belongs_to :parent

Something like this:

p = Parent.where(:name => 'Diana').includes(:children, :order => 'd_o_b DESC')

That way when I call p.children I am getting an array of objects ordered by birth, and not by their database ID.

Or do I just need to sort my array afterward?

Don
  • 746
  • 6
  • 18

1 Answers1

1

In your Parent model, change the has_many to:

has_many :children, :order => 'd_o_b DESC'

Then anytime you access the children association for a parent record (e.g., @parent.children), they'll be in descending order of date of birth.

lurker
  • 56,987
  • 9
  • 69
  • 103
  • `:order` was deprecated in `has_many` in Rails 4, updated answer available [here](http://stackoverflow.com/a/18284635/19794) – jasondoucette Nov 14 '16 at 20:14