编辑:在答案末尾添加奖金
嗯,你的问题对我来说很有趣,所以我决定自己尝试一下。
这可以正常工作:
1)产品迁移:
create_table :products do |t|
t.string :name
t.integer :cents, :default => 0
t.string :currency
t.timestamps
end
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
3) Form:
<%= 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 %>
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
BONUS:
如果您想添加货币汇率:
1) 你的 gemfile
gem 'json' #important, was not set as a dependency, so I add it manually
gem 'google_currency'
2)初始化器
在初始化程序文件夹中创建 Money.rb 并将其放入其中:
require 'money'
require 'money/bank/google_currency'
Money.default_bank = Money::Bank::GoogleCurrency.new
重新启动你的服务器
3) Play!
无论你在哪里,都可以兑换货币。
Product.first.price.exchange_to('USD')
显示效果良好:
Product.first.price.format(:symbol => true)