【问题标题】:Rails: How to use sum and multiple models to get the total order valueRails:如何使用 sum 和多个模型来获取总订单价值
【发布时间】:2019-12-26 14:28:16
【问题描述】:

我想按每个用户显示@amount_spent@amount_received。我已经用@amount_spent = Reservation.where(user_id: @user.id).sum(:total)完成了第一部分

现在我还想显示@amount_received,因为我使用的是 Stripe Connect。

我尝试过类似的方法:

@user = User.find(params[:id])
@products = @user.products
@amount_received = @products.reservations.sum(:total)

但是当我尝试将reservations@products 一起使用时,我收到#<Product::ActiveRecord_Associations_CollectionProxy:0x00007f50b8709fa8> 错误。

是否有更好的方法或其他方法,可能使用范围?

用户模型:

has_many :products
has_many :reservations

产品型号:

has_many :reservations

预留模式:

belongs_to :user
belongs_to :product

【问题讨论】:

  • 请向我们展示模型关系或相关架构部分。
  • 我添加了模型关系。

标签: ruby-on-rails ruby join activerecord


【解决方案1】:

您不能调用@products.reservations 来获取所有预订,因为@products 是一个关系(一个集合),您可以在单个对象上调用has_many 方法。相反,您需要使用 SQL JOIN(在 ActiveRecord joins 中实现)来获取所有相关的预留并将它们的总数相加:

@products.joins(:reservations).sum('reservations.total')

查看更多:

【讨论】:

    【解决方案2】:

    您获得异常的原因是因为 .reservations 只能在单个产品上调用。不在产品集合上。以下应该有效:

    @amount_received = Reservation.where(product_id: @products).sum(:total)
    

    通常您会指定要选择的列,但默认为 id。意思是.where(product_id: @products) 产生与.where(product_id: @products.select(:id)) 相同的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      相关资源
      最近更新 更多