Re: [問題] RoR 關於 資料庫 query 的問題
※ 引述《godfat (godfat 真常)》之銘言:
這邊可以簡化:
: pp data = Order.between('1001', '1002').group_by{ |order| order.date }.
: map{ |date_orders|
: {:date => date_orders.first,
: :items => [:location, :kind].inject({}){ |items, msg| items.merge(
: date_orders.last.inject({}){ |result, order|
: category = order.send(msg)
: result[category] ||= { :quantity => 0,
: :price_total => 0 }
: result[category][:quantity] += 1
: result[category][:price_total] += order.price
: result
: })
: }
: }
: }
一次處理完所有的 category, 就不用 merge 了,複雜度可以減半:
pp data = Order.between('1001', '1002').group_by{ |order| order.date }.
map{ |date_orders|
{:date => date_orders.first,
:items => date_orders.last.inject({}){ |result, order|
[:location, :kind].each{ |msg|
category = order.send(msg)
result[category] ||= { :quantity => 0,
:price_total => 0 }
result[category][:quantity] += 1
result[category][:price_total] += order.price
}
result
}
}
}
不過這樣 CD/DVD 和 台北/台中 的排序可能會亂掉,
而且他本來就是 hash, 不可以對他的順序有所期待。
要解決排序問題的話,
location 和 kind 就不能混在一起,可以用:
category = order.send(msg)
result[msg] ||= {}
result[msg][category] ||= { :quantity => 0,
:price_total => 0 }
result[msg][category][:quantity] += 1
result[msg][category][:price_total] += order.price
加上一個 location/kind 的分類。輸出的部份,就可以針對
CD/DVD 或是 台北/台中排序:
File.open('order.html', 'w') <<
data.map{ |row|
delimiter = "<br/>\n#{' '*row[:date].to_s.size}"
row[:date].to_s +
row[:items].map{ |item|
item.last.inject([]){ |result, info|
result << " #{info.first} #{info.last[:quantity]} 總價:#{info.last[:price_total]}"
result
}.sort.join(delimiter) # 這邊排序
}.join(delimiter)
}.join("<br/>\n")
--
「行け!Loki!」(rocky ロッキー)
-Gurumin ぐるみん 王子? XD
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.135.28.18
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 4 之 4 篇):
Ruby 近期熱門文章
PTT數位生活區 即時熱門文章