Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby On Rails: Order by child attribute

If I have a model A that has an attribute X and a child model of A called B with an attribute Y, how can I order all the instances of A by Y and X?

like image 762
rhfannnn Avatar asked Dec 21 '22 17:12

rhfannnn


2 Answers

You can use default_scope to order all of your model instances by an association. You just pass the associated model name to the :includes param and adjust your order param:

default_scope :include => 'record', :order => 'records.attribute'

However, default_scope isn't highly recommended. A cleaner approach would be to create a class method in your parent model that you can call from your controllers:

def self.all_ordered_by_child
   includes(:records).order('records.attribute DESC')
end

You will just need to update all instances that call all records from the parent model.

like image 154
jordanandree Avatar answered Jan 07 '23 06:01

jordanandree


I'm going to use lowercase letters instead:

a_instances.sort_by{|a| [a.b.y, a.x]}
like image 33
Peter Avatar answered Jan 07 '23 06:01

Peter