我正在尝试计算多种产品的运输尺寸。我想返回@tempLength
和@tempWidth
的最大值,并在我的循环中总结所有@tempHeight
:
@tempLength = 0
@tempWidth = 0
@tempHeight = 0
params[:rate][:items].each do |item|
item = item[:product_id]
puts "Item details"
puts item
@productDimensions = Product.where(:product_id => item).first
@tempLength = @productDimensions.length
@tempWidth = @productDimensions.width
@tempHeight = @productDimensions.height
# tempLength = maximum length value
# tempWidth = maximum width value
# tempHeight = sum of all heights
end
我知道我必须使用sum(&:symbol)
,但我被困住了。什么是最好的方法?
答案 0 :(得分:3)
这里可能有帮助
@tempLength = 0
@tempWidth = 0
@tempHeight = 0
params[:rate][:items].each do |item|
item = item[:product_id]
puts "Item details"
puts item
@productDimensions = Product.where(:product_id => item).first
@tempLength = @tempLength + @productDimensions.length
@tempWidth = @tempWidth + @productDimensions.width
if @productDimensions.height > @tempHeight
@tempHeight = @productDimensions.height
end
end
# @tempLength = total of all tempLength values
# @tempWidth = total of all tempHeight values
# @tempHeight = keep highest value
答案 1 :(得分:1)
也许另一个可能会带来更好表现的建议:
@tempLength = 0
@tempWidth = 0
@tempHeight = 0
product_ids = []
params[:rate][:items].each do |item|
product_ids << item[:product_id]
end
# Filter products according to collected product_ids
@products = Product.where(:product_id => product_ids)
# Let ActiveRecord do the work
@tempLength = @products.sum('length')
@tempWidth = @products.sum('width')
@tempHeight = @products.maximum('height')
# @tempLength = total of all tempLength values
# @tempWidth = total of all tempHeight values
# @tempHeight = keep highest value