render multiple HTML tables
I have a Rails Table, called Sales, that I would like to render in a sequence of HTML tables on a single HTML page.
The Sales Table contains a list of sales transactions made by SalesPeople (salesperson_id is a field within each Sales record), and I would like to list each of their Sales records grouped in HTML tables, by salesperson_id. Similar to this:
Sales Person : Bob
*PRODUCT* *QUANTITY*
Widgets 17
Cogs 5
Screws 100
Sales Person : Jim
*PRODUCT* *QUANTITY*
Bozzles 49
Widgets 20
Screws 250
Flurbs 22
Now, my first thoughts were that I would 'find_all' sales transactions meeting my criteria, and then loop through the returned array, and rendering each SalesPerson using a _partial, but I'm aware I can only perform one render per result.
Is it possible to achieve this using a single render, do I need 开发者_JS百科some HTML / JavaScript magic, or is there another solution?
Thanks.
You can only render once like you said, so you cant render for each sales person.
You can use a single render if you pass the sales transactions to the partial (refer to http://guides.rubyonrails.org/layouts_and_rendering.html#using-render 3.4.4 passing local variables), but inside that partial you will do the "html/javascript magic" anyway.
Inside the partial, you need to use the ruby foreach to print each table, like this:
<% salesTransactions.each do |transaction| %>
<table>
<tr><td>Product</td><td>Quantity</td></tr>
<tr><td>Widgets</td><td><%= transaction.widgets %></td>
//.....
</table>
<% end %>
I am guessing you want to reuse that partial somewhere else? If not, you can simple do all the stuff inside the view.
OK, I figured out a way to achieve what I want to achieve by using group_by, with help from this RailsCast,
http://railscasts.com/episodes/29-group-by-month (#29 of a brilliant series)
So, I use group_by to group the sales by salesperson_id, then in my view,
<% @groupedSales.each do |salesperson_id, sales| %>
<h2><%= Salesperson.find(salesperson_id).name %></h2>
<table>
<thead>
<tr>
<th>Date</th>
<th>Product</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<% sales.each do |sales_activity| %>
<tr>
<td><%= sales_activity.created_at.strftime('%d/%m/%y') %></td>
<td><%= sales_activity.product %></td>
<td><%= sales_activity.quantity %></td>
</tr>
<% end %>
</tbody>
</table>
<% end %>
精彩评论