我正在开发一个非常基本的购物车系统。

我有一个表items,它的列价格类型为整型。

我在视图中显示包含欧元和美分的价格时遇到了麻烦。在Rails框架中处理货币时,我是否遗漏了一些明显的东西?


当前回答

下面是一个利用composed_of (ActiveRecord的一部分,使用ValueObject模式)和Money宝石的简单方法

你需要

金钱宝石(4.1.0版本) 一个模型,例如Product 模型(和数据库)中的整数列,例如:price

把这些写进你的产品中。rb文件:

class Product > ActiveRecord::Base

  composed_of :price,
              :class_name => 'Money',
              :mapping => %w(price cents),
              :converter => Proc.new { |value| Money.new(value) }
  # ...

你会得到:

Without any extra changes, all of your forms will show dollars and cents, but the internal representation is still just cents. The forms will accept values like "$12,034.95" and convert it for you. There's no need to add extra handlers or attributes to your model, or helpers in your view. product.price = "$12.00" automatically converts to the Money class product.price.to_s displays a decimal formatted number ("1234.00") product.price.format displays a properly formatted string for the currency If you need to send cents (to a payment gateway that wants pennies), product.price.cents.to_s Currency conversion for free

其他回答

绝对的整数。

即使BigDecimal技术上存在,1.5仍然会在Ruby中给你一个纯浮点数。

处理货币的常见做法是使用十进制类型。 下面是“使用Rails进行敏捷Web开发”中的一个简单示例。

add_column :products, :price, :decimal, :precision => 8, :scale => 2 

这将允许您处理从-999,999.99到999,999.99的价格 你可能还想在你的项目中包括一个验证,比如

def validate 
  errors.add(:price, "should be at least 0.01") if price.nil? || price < 0.01 
end 

检查你的价值观。

Ruby和Rails的简单代码

<%= number_to_currency(1234567890.50) %>

OUT PUT => $1,234,567,890.50

我是这样用的:

number_to_currency(amount, unit: '€', precision: 2, format: "%u %n")

当然,货币的符号、精度、格式等都取决于每种货币。

如果你正在使用Postgres(因为我们现在已经是2017年了),你可能想尝试一下他们的:money列。

add_column :products, :price, :money, default: 0