views:

23

answers:

1

I Like to add a method to my has_many relation in the way that it is applyed on the relation object.
I got an Order wich :has_many line_items
I like to write things like
order.line_items.calculate_total # returns the sum of line_items
this I could do with:
:has_many line_items do def calculate_total ... end end
but this would not be applyed to named_scopes like payalbes_only:
order.line_items.payables_only.calculate_total
here calculate total would receive all line_items of order and not the scoped ones from payables_only-scope. My log tells me that the paybles_only scope is even not applied to the sql.

+1  A: 

One, albeit ugly, way to accomplish this would be to use class_eval on the Array class, for instance:

Array.class_eval do
  def calculate_total
    total = 0
    self.each do |item|
      total = total + item.value if item.class.to_s == 'LineItem'
    end
    return total
  end
end 
Patrick Klingemann