ActiveRecord query: sum order by model included

  • Has_many project: items
  • Item belongs to: project

I am trying to get projects sorted by the total price of their respective items. Sort of:

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

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

+4
source share
2 answers
 Project.find_by_sql " select projects.* from projects left join ( select project_id, sum(price) as items_sum from items group by project_id) as sums on project.id = sums.project_id order by sums.items_sum 

Above SQL should work well on most database systems (MySQL, PostgreSQL, ...).

The AR includes entry is mainly used as a reliable boot solution. And I'm not sure if you can use it this way - to arrange the records of the parent table.

0
source

I haven't tried v3 stuff yet, but I would suggest that it would be something like

 Product.joins(:items).group('products.id').order('SUM(items.price)') 
+8
source

Source: https://habr.com/ru/post/1343776/


All Articles