ruby-on-rails - 一次查询中的 Rails 客户端订单历史记录

标签 ruby-on-rails postgresql associations aggregate-functions

我正在尝试生成客户资料页面。该页面包括客户订单历史记录、最近的订单及其历史总计。我一直在 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/

相关文章:

ruby-on-rails - 将 RVM 与 GVim(奶油色)一起使用 : rvm command not found

ruby-on-rails - 正在考虑 Sphinx 分面搜索实现示例?

java - 错误 :org. postgresql.util.PSQLException :ERROR: column userinfo0_. dtype 不存在

ruby-on-rails - Rails 进阶协会

nhibernate - 使用 nhibernate(和 queryover)急切地获取多个嵌套关联

ruby-on-rails - 为什么 foreign_key 被忽略了?

ruby-on-rails - 如何开始性能测试

ruby-on-rails - 将文件排除在 Capistrano 部署之外,同时仍在 Git 的版本控制之下

postgresql 从内部函数运行外部 sql 脚本

java - 如何使用 JPA 查询使 PostgreSQL 不区分大小写