我正在使用money gem,我想知道如何獲得像23.45,10.00,0.32這樣的價格在一個字段中顯示爲dollar.cents?我想我的仙田成爲只是價格(錢或美元&美分)。如何獲得完整的金錢寶石
這裏是我的代碼:
我用錢的寶石composed_of型號:
class Price < ActiveRecord::Base
attr_accessible :name, :date, :cents, :currency
belongs_to :user
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :currency, :presence => true
validates :cents, :presence => true
validates :date, :presence => true
default_scope :order => 'prices.created_at DESC'
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
的形式(切出簡潔部分):
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :date %><br />
<%= f.date_select :date %>
</div>
<div class="field">
<%= f.label :cents %><br />
<%= f.text_field :cents %>
</div>
<><div class="field">
<%= f.label :currency %><br />
<%= f.select(:currency,major_currencies(Money::Currency::TABLE),
{:include_blank => 'Select a Currency'}) %>
</div>
我的遷移或價格表:
class CreatePrices < ActiveRecord::Migration
def self.up
create_table :prices do |t|
t.integer :user_id
t.string :name
t.date :date
t.integer :cents, :default => 0
t.string :currency
看起來好像我缺少一列或其他東西。甚至假設只有美分?不知道,所以我需要你的幫助。
謝謝你抽出時間。
也許這可能有助於:http://stackoverflow.com/questions/4798651/rails-money-gem-converts-all-amounts-to-zero/4800159 – apneadiving 2011-06-07 06:10:23
只需看看它:你有DB和美分貨幣在視圖中(以其爲準),因此23.45以貨幣== 2345美分。 – santuxus 2011-06-07 09:47:43
@apneadiving我實際上遵循了你接受的答案讓我開始,創造了這樣的一切,仍然得到了上述問題。 – LearningRoR 2011-06-07 13:30:21