Bit of a beginner question here...in my rails app I have a model for parts and I want admin to be able to apply a discount to the price of the part if they want to. The value of the discount in my parts model is an integer. I have a method inside my part model called apply_discount
class Part < ActiveRecord::Base
has_many :order_items
belongs_to :category
default_scope { where(active: true)}
def apply_discount
new_price = self.discount.to_decimal * self.price
self.price - new_price
end
The error I am getting is "undefined method `to_decimal' for 10:Fixnum" whenever you put in a percentage of the discount. Any ideas how I can get the discount proper to convert into a float or to a decimal? Thanks
There's no to_decimal
method for integers, but there's a to_f
(to float). You'll need to divide by 100 to get the discount percentage to work.
Also, you don't need to use self.
unless you're assigning.
def apply_discount
price - ( discount.to_f / 100 * price )
end