Rails Ruby 中通过 getter 和 setter 表示百分比

Representing percentages through getters and setters in Ruby on Rails

在我的 Rails 应用中,我希望用户能够输入 0.0 到 100.0 之间的小数百分比值。在数据库中,我想将它们存储为0.00到1.00的小数,这样计算更容易。

我目前正在通过模型中的 getter 和 setter 来执行此操作。但是,当我在模型中编写派生属性时,它们最终使用 0-100 值而不是 0-1,这违背了将其存储在 0-1 值中以便于计算的目的:

# in the model `quote.rb`

def discount=(value)
  write_attribute :discount, value.to_f / 100
end
def discount
  read_attribute(:discount).to_f * 100
end

def final_price
  price * (1 - discount)
  # this generates a wrong value, 
  # because if the user inputs discount as 50 to represent 50%, 
  # the final price will be `price * -49`
end

关于实现此目标的更好方法有什么想法吗?

我会使用小数列(以避免 issues with floats and rounding)来存储原始值(作为百分比)并避免转换。

然后您可以使用以下方法简单地计算净价:

def final_price
  price * (discount || 100 * 0.01)
end

在处理向用户呈现输出时,您希望查看 money gem,因为它可以更轻松地处理区域设置和多种货币。