I am trying to show the total price of an order, but i keep getting
this problem;
wrong number of arguments (1 for 2)
On this method, in the order.rb model;
def total
order_items.sum { |item| item.total }
end
An order consists of several order_items via a has_many relationship,
the total method found in order_items.rb looks like this;
def total
self.quantity * self.product.price
end
And as you can guess, an order_item refers to a product.
I am simply calling this in the view;
for orders in @orders do
order.total
end
I just cant seem to get it working, help is greatly appreciated.
Pratik is likely right, but I wanted to correct his use of #inject in this case:
order_items.inject(0.0) { |total, item| total + item.total }
Without a starting point (0.0), the initial value is taken as the first element which is an Item not a number. Also, it is unnecessary to use += since the local value of total isn't what's important, but the value of the block (i.e., the last expression value) so just using + is sufficient.
As for "why" the order_items.sum isn't working, your definition of #total is not a database column so the total can't be obtained from the generated SQL directly (at least not without duplicating the definition of total and that wouldn't be very DRY, would it?).