I’m trying to find a solution for the following problem:
I have to list 3 things - companies’ names, total amount each company
owes, total number of containers that belong to each company - using
given invoices that still have a balance (they are outstanding). All
this in a given period of time (filter).
An invoice looks like this:
class Invoice < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
belongs_to :company
and it has company_id, amount and balance. An invoice has 1 or many line
items, each line item stands for a container:
class LineItem < ActiveRecord::Base
belongs_to :invoice
belongs_to :container
class Container < ActiveRecord::Base
has_many :line_items
Fetching the company’s name and calculating the total amount owed per
company has worked so far, but I’m having a problem with adding up the
containers. If I could count the line items, that would result in
containers’ number. To do so, I’ve created named scopes:
named_scope :filter, lambda { |invoice_filter| {:conditions =>
invoice_filter.sql_conditions}}
named_scope :outstanding, :conditions => [“invoices.balance != ?”, 0]
named_scope :totals, :include => :line_items,
:select => ‘sum(invoices.amount) as amount, company_id, count(*) as
containers_count’,
:joins => :line_items,
:group => ‘invoices.company_id’
:filter and :outstanding refer to invoices that haven’t yet been payed
(so they have a balance) in a certain period of time (from, to). :totals
is the one grouping the companies by id, while summarizing their
invoices’ amount and counting the line items as containers_count
(attr_accessor :containers_count).
The controller is:
@invoice_filter = InvoiceFilter.new(params[:filter])
@invoices = Invoice.filter(@invoice_filter).outstanding.totals
and the view:
<% for invoice in @invoices do %>
<%= invoice.containers_count %>
The problem is that containers_count doesn’t get a value, hence nothing
is shown in the 3rd column. I’m assuming that amount works because
invoice has an amount field, but it doesn’t have a containers_count
field. Any idea on how the :totals named scope might be improved? Or is
there another solution for this?