简体   繁体   中英

Rails. How can I make .sum method faster?

I need to calculate total value for column :total_value in Order model. I try to do:

Order.where("created_at > :day", {:day => 10.day.ago}).where(user_id: 3, state: 'collected').sum(:total_value)

It works for me. But... Is there any possibility to do it faster? Should I add indexes for :total_value and :created_at columns. Does it make a sense?

I'm not really that well aware of Rails internal optimizations, but the thing that first comes into my mind is combining the where clauses into one instead of two. Now it has to first create a result set for the first where and then apply other where on that set (assuming that Rails doesn't optimize it already).

Creating index for total_value makes no sense since you aren't looking for anything based on that column.

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