Dav*_*vid 9 ruby rubygems currency ruby-on-rails ruby-on-rails-3
我正在尝试使用money gem在我的应用程序中处理货币,但我遇到了一个奇怪的错误.这就是我在"记录"模型中的含义:
composed_of :amount,
:class_name => "Money",
:mapping => [%w(cents cents), %w(currency currency_as_string)],
:constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) },
:converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }
Run Code Online (Sandbox Code Playgroud)
amount是一个整数.
当我创建一个新记录时,它会忽略我在amount字段中输入的任何值,并将其默认为0.我需要在表单中添加一些内容吗?
我使用的是rails 3.0.3,而money gem版本是3.5.5
apn*_*ing 22
编辑:在答案结束时添加奖金
好吧,你的问题对我来说很有趣,所以我决定尝试自己.
这工作正常:
1)产品迁移:
create_table :products do |t|
t.string :name
t.integer :cents, :default => 0
t.string :currency
t.timestamps
end
Run Code Online (Sandbox Code Playgroud)
2)产品型号
class Product < ActiveRecord::Base
attr_accessible :name, :cents, :currency
composed_of :price,
:class_name => "Money",
:mapping => [%w(cents cents), %w(currency currency_as_string)],
:constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) },
:converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }
end
Run Code Online (Sandbox Code Playgroud)
3)表格:
<%= form_for(@product) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :cents %><br />
<%= f.text_field :cents %>
</div>
<div class="field">
<%= f.label :currency %><br />
<%= f.select(:currency,all_currencies(Money::Currency::TABLE), {:include_blank => 'Select a Currency'}) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Run Code Online (Sandbox Code Playgroud)
4)产品助手(手工制作):
module ProductsHelper
def major_currencies(hash)
hash.inject([]) do |array, (id, attributes)|
priority = attributes[:priority]
if priority && priority < 10
array ||= []
array << [attributes[:name], attributes[:iso_code]]
end
array
end
end
def all_currencies(hash)
hash.inject([]) do |array, (id, attributes)|
array ||= []
array << [attributes[:name], attributes[:iso_code]]
array
end
end
end
Run Code Online (Sandbox Code Playgroud)
如果您想添加货币汇率:
1)你的宝石文件
gem 'json' #important, was not set as a dependency, so I add it manually
gem 'google_currency'
Run Code Online (Sandbox Code Playgroud)
2)初始化器
在你的初始化文件夹中创建money.rb并将其放入:
require 'money'
require 'money/bank/google_currency'
Money.default_bank = Money::Bank::GoogleCurrency.new
Run Code Online (Sandbox Code Playgroud)
重启你的服务器
3)玩!
无论你在哪里,你都可以兑换这笔钱.
Product.first.price.exchange_to('USD')
Run Code Online (Sandbox Code Playgroud)
显示良好的渲染:
Product.first.price.format(:symbol => true)
Run Code Online (Sandbox Code Playgroud)