1

这里有一个初学者问题......在我的 Rails 应用程序中,我有一个零件模型,我希望管理员能够根据需要对零件的价格进行折扣。我的零件模型中的折扣值是一个整数。我的零件模型中有一个名为 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

每当您输入折扣百分比时,我得到的错误是“10:Fixnum 的未定义方法`to_decimal'”。任何想法如何获得适当的折扣以转换为浮点数或小数?谢谢

4

1 回答 1

8

整数没有to_decimal方法,但有一个to_f(浮动)。您需要除以 100 才能使折扣百分比起作用。

self.此外,除非您正在分配,否则您不需要使用。

def apply_discount
  price - ( discount.to_f / 100 * price )
end
于 2016-03-19T01:00:55.323 回答