Reputation: 103
I'm trying to implement a discount for each individual product in a catalogue. I added new field to Products table - discount. How do I recalculate product.price if discount.present?
I tried to add helper to product.rb:
def price
old_price = self.price
if self.discount.present?
self.price -= self.price / self.discount
else
old_price
end
But it gets me to "Stack level too deep" error
Upvotes: 0
Views: 959
Reputation: 14900
You get this error because price
is constantly referencing itself. You would be much better off by creating a new method to display the price.
def price_with_discount
return self.price if self.discount.nil? || self.discount.zero?
self.price - (self.price / self.discount)
end
And then you use that in your view
<%= product.price_with_discount %>
Upvotes: 4