简体   繁体   中英

group by sum of products of child model attributes

Document has_many :items

Item belongs_to :document

I need to find documents, in which the sum of products of its items.quantity * items.value_net is greater than certain value.

I tried scope:

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

But it is wrong. I must be missing something obvious.

You are looking for having (not tested):

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

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