我正在尝试生成客户资料页面。该页面包括客户订单历史记录、最近的订单及其历史总计。我一直在 Customer.where_completed 上运行总和、计数和平均值,但这触及该数据库 3 次。我觉得必须有更好的方法吗?
@customers_total_spent = @customer.orders.where_completed.sum(:sale)
@customers_average_per_order = @customer.orders.where_completed.average(:sale)
@customers_total_orders = @customer.orders.where_completed.count(:sale)
客户
class Customer < ActiveRecord::Base
has_many :orders
end
订单
class Order < ActiveRecord::Base
belongs_to :customer
scope :completed,-> { where.not(completed_at: nil) }
end
最佳答案
你应该试试这个
orders_completed = @customer.orders.where_completed.pluck("sum(sale), avg(sale), count(sale)").flatten
@customers_total_spent = orders_completed[0]
@customers_average_per_order = orders_completed[1]
@customers_total_orders = orders_completed[2]
关于ruby-on-rails - 一次查询中的 Rails 客户端订单历史记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32736653/