activerecord - Group by name, count and total, and display it in a view using Rails -
i thought wasn't rookie anymore, until stumbled upon this.
i'm trying load html list, grouping shops per user , displaying per shop, number of receipts , total amount.
in sql group by, trying load code below, within shop model, rails console.
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) number_of_receipts,sum(receipts.total) total').group('shops.id') query end here output
>> shop.group_receipts(302).all (2.0ms) select id "shops" (3.0ms) select shop_id "receipts" (receipts.id in (select receipts.id 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 user_companies.user_id = 302)) , (receipts.is_manual null or receipts.is_manual=false) order receipts.created_at desc shop load (2.0ms) select shops.name,count(receipts.id) number_of_receipts,sum(receipts.total) total "shops" inner join "receipts" on "receipts"."shop_id" = "shops"."id" (shops.id in (16)) group shops.id [#<shop name: "kirlin osinski , dooley">] if query seems right, why that output not name, 10, 1000 ?
that greceipt struct find on method definition intends create structure that, can later access gs.name, gs.number_of_receipts, gs.total, cannot understand how load list of objects of struct type output presented above :-s.
anyone rescue?
with of forum, understood problem within rails console.
i ended with
model:
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) number_of_receipts,sum(receipts.total) total').group('shops.id') query end controller:
@receipts_per_shop = shop.group_receipts(current_user) partial view _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> partial view _receipt_per_shop
<% @receipts_per_shop.each |rs| %> <tr> <td><%= rs.name %></td> <td><%= rs.number_of_receipts %></td> <td><%= rs.total %></td> </tr> <% end %>
Comments
Post a Comment