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?
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.
I'm going to use lowercase letters instead:
a_instances.sort_by{|a| [a.b.y, a.x]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With