I’m working on generating quarterly royalty reports for authors. I have a Report model (not backed by a database table) that I’m using to display the report for specific authors based on the year and quarter. I’m routing that to author/:author_id/:reports/:year/:quarter
I’ve got some pretty ugly code in my controller right now, for the sake of getting things working. I can refactor later:
def show
@author = Author.find(params[:author_id])
#find the orders that took place in the current quarter and year for the report
@orders = Order.get_current_orders(quarter_range, params[:year])
#find only the products that apply for the current author
@author_products = @author.products
#find only the line_items that match the current quarter's orders and the author's products
@line_items = LineItem.find_all_by_order_id_and_product_id(@orders, @author_products)
#group the line items by product
@line_items_by_product = @line_items.group_by { |l| l.product_id }
end
That let’s me do this in my view:
<%= @line_items_by_product.each do |product, line_item | %>
<h3><%= product %></h3>
<% line_item.each do |line_item| %>
<%= line_item.quantity %> <br />
<% end %>
<% end %>
Two things I need to fix. Right now, product just returns the product id, not the title (it’s stored in the products table, not the line_items table). I can’t access product.title here obviously, but I need to get the title in the grouping.
My second issue is that instead of just looping over the quantity of every single line item, I want to total the quantity of each line item and just display that. So in stead of getting , 1, 10, 55 … I just want 66. I tried array#inject, but I’m not grasping the syntax.
And, that all be said … I’m sure I’m doing more work than I need to. I started with a lot of the controller code in the model but was having a lot of undefined method errors. Any advice or help would be appreciated.
I agree that you need to refactor your code, and I’m only offering these answers to your specific questions – these are not my overall recommendations.
First Problem
Remember this is Ruby, a Product instance is just as valid to group by as the Integer that you’re currently using. So, you can change your
group_bycall to:…and then change your view to…
Second Problem