简体   繁体   中英

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?

我还没有尝试过v3的东西,但我认为它会是这样的

Product.joins(:items).group('products.id').order('SUM(items.price)')
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 DB systems (MySQL, PostgreSQL, ...).

AR record includes is mostly used as eager loading solution. And I am not sure if you can use it that way - to order records of parent table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM