Discounted total

Hi again,

Every customer has a discount level assigned to them. when they add
items to the cart and on checkout (or when admin views all orders), I
would like to show the total after discount.
In the orders table, I insert the discount level at the time of order.
I ended up calculating the discounted total in about 3 or 4 of my
views and I thought that there should be a better way of doing this.
My logic tells me that the calculation should be done within the cart
class, where also the total is calculated (maybe my logic is wrong).
So, I added this to my cart.rb class:

def discounted_total
subtotal =
discount = / 100
subtotal = (subtotal * discount)
@discounted = - subtotal

But now I get this error:
NoMethodError in Cart#view_cart
Showing app/views/cart/view_cart.rhtml where line #31 raised:

You have a nil object when you didn’t expect it!
The error occurred while evaluating
Extracted source (around line #31):


two_dec(@cart.discounted_total) %>

app/models/cart.rb:38:in `discounted_total’

So, my question is:
How should I accomplish this? Any ideas how my code could be better?
And how do I get the order.rb see the same discounted total?


I suppose it would be because @cart is not available within cart.rb.
Try instead? e.g

def discounted_total
subtotal =
discount = / 100
subtotal = (subtotal * discount) - subtotal

not sure how your cart class is constructed and its relationship with
the Customer class so this may not be correct when dealing with
getting the discount amount.

This works great in my cart views (view_cart and checkout). Then I
tried to duplicate it in my order.rb class and it doesn’t work again.
Most of the time I get an error that I have a nil object.
My orders table has the following columns: customer_id, discount,

The order.rb code is:

def total
order_items.inject(0) {|sum, n| n.price * n.amount + sum}

def discount
current_order = Order.find(params[:id])
discount =

def discounted_total
subtotal =
discount = / 100
subtotal = (subtotal * discount) - subtotal

The total is calculated exactly the same as in the cart. The
relationships are exactly as the cart but with order_items:
has_many :order_items
has_many :products, :through => :order_items
belongs_to :customer

And I tried to use @order.discounted_total in my views but it doesn’t
Why wouldn’t it work here when it worked in mt cart? and how should I
fix it?