我以为我不再是新手了,直到我偶然发现了这一点。
我正在尝试加载一个HTML列表,为每个用户分组商店并显示每个商店,收据数量和总金额。
在Sql中,我可以使用group by轻松完成此操作,因此我尝试将以下代码加载到我的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 :(得分:0)
在forum的帮助下,我明白问题出在rails console中。
我最终得到了
模型:
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 %>