Re: [問題] RoR 關於 資料庫 query 的問題

看板Ruby作者 (godfat 真常)時間16年前 (2008/10/05 03:27), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串4/4 (看更多)
※ 引述《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#{'&nbsp;'*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
文章代碼(AID): #18vyErbD (Ruby)
文章代碼(AID): #18vyErbD (Ruby)