ruby 如何根据计算对ActiveRecord查询进行排序

mbskvtky  于 11个月前  发布在  Ruby
关注(0)|答案(2)|浏览(112)

我想列出面包店的销售糕点的数量。
为了对它们进行排名,我会将每个糕点的可用糕点数量乘以它们在销售中的百分比。面包店可能有0-10个糕点在销售。例如:

bakery1.pastry1 = 100
bakery1.pastry1_discount = 10 (%)
bakery1.pastry2 = 50
bakery1.pastry2_discount = 20 (%)
(2 pastries on sale)

字符串
(100 x 10)+(50 x 20)= 2000..将首先列出

bakery2.pastry1 = 10
bakery2.pastry1_discount = 40
bakery2.pastry2 = nil
bakery2.pastry2_discount = nil
(only 1 pastry on sale, etc)


10 x 40 = 400..列出第二名

bakery3.pastry1 = 10
bakery3.pastry1_discount = 20
bakery3.pastry2 = nil
bakery3.pastry2_discount = nil


10 x 20 = 200..最后列出
那么,我如何通过某些属性值的乘法之和来排序Bakery呢?
到目前为止,我知道sort_by对数据库的内存有很大的影响。
更新:.它必须是(糕点可用-糕点出售)x折扣

jei2mxaa

jei2mxaa1#

就我对问题的理解。这是解决方案,

class Bakery
  attr_accessor :name, :pastries

  def initialize(name, pastries)
    @name = name
    @pastries = pastries
  end

  def order_value
    pastries.sum { |_, values| values[:pastry].nil? ? 0 : values[:pastry] * values[:discount] }
  end

  def self.order(*bakeries)
    bakeries.max_by(&:order_value)
  end
end

字符串

示例

bakery1 = Bakery.new("Bakery1", { pastry1: { pastry: 100, discount: 10 },pastry2: { pastry: 50, discount: 20 } })
bakery2 = Bakery.new("Bakery2", { pastry1: { pastry: 10, discount: 40 } })
bakery3 = Bakery.new("Bakery3", { pastry1: { pastry: 10, discount: 20 } })

highest_order_bakery = Bakery.order(bakery1, bakery2, bakery3)

puts "#{highest_order_bakery.name}: #{highest_order_bakery.order_value} order value"

highest_order_bakery.pastries.sort_by { |_, values| -values[:discount] }.each do |pastry, values|
 puts "  #{pastry}: #{values[:discount]}% discount"
end

ivqmmu1c

ivqmmu1c2#

我将使用sort_by代替order,并创建了一个示例方法来计算可用的糕点

class Bakery
 # method to calculate pastery availability
 def pastery_count
   count = 0
   self.pastery.each do |ps|
     count = count + ps.count.to_i * ps.discount.to_i
   end

   count
 end
end

字符串
然后调用sort_by

Bakery.sort_by{|br| br.pastery_count}


您也可以将合并与where子句结合使用

Bakery.where(...).sort_by{|br| br.pastery_count}

相关问题