1
我以爲我不再是菜鳥,直到我偶然發現它。按名稱,數量和總數分組,並使用Rails將其顯示在視圖中
我試圖加載一個html列表,將每個用戶分組並顯示每個商店,收據數量和總金額。
在Sql中,我會通過一個組輕鬆完成這個工作,所以我試圖在我的Shop Model中將以下代碼加載到我的Rails控制檯中。
def self.group_receipts(user, search_hash=nil)
shop_ids = Shop.pluck(:id) & Receipt.from_companies(user, search_hash).pluck(:shop_id)
#greceipt means Grouped Receipt
greceipt = Struct.new(:name, :number_of_receipts, :total)
query = Shop.joins(:receipts).where('shops.id in (?)',shop_ids).select('shops.name,count(receipts.id) as number_of_receipts,sum(receipts.total) as total').group('shops.id')
query
end
這裏是我的輸出
>> Shop.group_receipts(302).all
(2.0ms) SELECT id FROM "shops"
(3.0ms) SELECT shop_id FROM "receipts" WHERE (receipts.id IN (SELECT receipts.id
FROM receipts
INNER JOIN shops on shops.id=receipts.shop_id
INNER JOIN companies on companies.id = shops.company_id
INNER JOIN user_companies on user_companies.company_id = companies.id
WHERE user_companies.user_id = 302)) AND (receipts.is_manual is null or receipts.is_manual=false) ORDER BY receipts.created_at DESC
Shop Load (2.0ms) SELECT shops.name,count(receipts.id) as number_of_receipts,sum(receipts.total) as total FROM "shops" INNER JOIN "receipts" ON "receipts"."shop_id" = "shops"."id" WHERE (shops.id in (16)) GROUP BY shops.id
[#<Shop name: "Kirlin Osinski and Dooley">]
如果我的查詢似乎是所有的權利,這是爲什麼,我的輸出不是像name, 10, 1000
?
您在方法定義中找到的greceipt結構想要創建一個結構,以便稍後可以訪問gs.name,gs.number_of_receipts,gs.total,但我無法理解如何加載此對象的列表結構類型從上面顯示的輸出:-S。
任何人都可以拯救?