2013-05-03 48 views
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。

任何人都可以拯救?

回答

0

在此forum的幫助下,我瞭解到問題出在rails控制檯中。

我結束了

模型:

def self.group_receipts(user, search_hash=nil) 

    shop_ids = Shop.pluck(:id) & Receipt.from_companies(user, search_hash).pluck(:shop_id) 
    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 

控制器:

@receipts_per_shop = Shop.group_receipts(current_user) 

局部視圖_receipts_per_shop:

<table class="table table-striped"> 
    <thead> 
    <th><%=t 'activerecord.attributes.shop.name'%></th> 
    <th>#</th> 
    <th>Total</th> 
    </thead> 
    <% if @shops.present? %> 
     <%= render partial: '/shops/receipt_per_shop', collection: @receipts_per_shop %> 
    <% else %> 
     <tbody><tr><td colspan="3"><%= t('no_records') %></td></tr></tbody> 
    <% end %> 
</table> 

局部視圖_receipt_per_shop

<% @receipts_per_shop.each do |rs| %> 
    <tr> 
     <td><%= rs.name %></td> 
     <td><%= rs.number_of_receipts %></td> 
     <td><%= rs.total %></td> 
    </tr> 
<% end %> 
相關問題