Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord query: order by a sum on an included model

  • Project has_many :items
  • Item belongs_to :project

I'm trying to get the projects sorted by the total price of their respective items. Something like:

Project.includes(:items).order('SUM(items.price)')

With this code, ActiveRecord returns only the first project. What am I missing?

like image 674
Yannis Avatar asked Feb 25 '23 19:02

Yannis


1 Answers

I've not tried the v3 stuff out yet, but I'd assume it would be something like

Product.joins(:items).group('products.id').order('SUM(items.price)')
like image 85
Simon Avatar answered Feb 27 '23 07:02

Simon