【发布时间】:2011-06-07 04:51:30
【问题描述】:
我正在使用money gem,我想知道我如何才能在一个字段中显示 23.45、10.00、0.32 之类的价格为 Dollar.cents? 我希望我的 cents 字段变为只是价格(金钱或美元和美分)。
这是我的代码:
我的模型与金钱 gem 组成:
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
好像我错过了一个专栏或其他东西。它甚至假设是美分?不确定,所以我需要你的帮助。
感谢您抽出宝贵时间。
【问题讨论】:
-
只要看一下:您在 DB 中有美分,在视图中有货币(无论是哪个),所以 23.45 货币 == 2345 美分。
-
@apneadiving 我实际上遵循了你给我的公认答案让我开始,创造了这样的一切,但仍然遇到上述问题。
-
@santuxus 我也在想同样的事情,但我不知道如何配置它,所以我得到了全额。
标签: ruby-on-rails gem currency