【问题标题】:group by sum of products of child model attributes按子模型属性的乘积之和分组
【发布时间】:2016-03-22 14:52:27
【问题描述】:
Document has_many :items

Item belongs_to :document

我需要查找其items.quantity * items.value_net的乘积之和大于某个值的文档。

我试过范围:

scope :items_value_net_gteq, lambda { |value|
  joins(:items)
    .where('SUM(items.quantity * items.price_net) >= ?', value)
}

但这是错误的。我一定遗漏了一些明显的东西。

【问题讨论】:

    标签: mysql ruby-on-rails scope


    【解决方案1】:

    您正在寻找having(未测试):

    scope :items_value_net_gteq, ->(value) {
      joins(:items).group('documents.id').
        having('SUM(items.quantity * items.price_net) >= ?', value)
    }
    

    【讨论】:

    • 作用类似于魅力、+1 和接受(相差 10 秒,但仍是第一个回答)
    【解决方案2】:
    scope :items_value_net_gteq, lambda do |value|
      joins(:items).group("items.document_id")
             .having('SUM(items.quantity * items.price_net) >= ?', value)
    end
    

    【讨论】:

    • 非常感谢!赞成但必须接受@BroiState的回答,-他是“第一”:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多