Rails钱宝石和表单生成器

时间:2011-01-31 22:20:37

标签: ruby-on-rails forms rubygems currency formbuilder

我遇到了表单和money gem的问题。

这是我的问题:

  1. 我创建了一个具有“金额”字段的记录(映射到货币对象)。假设我输入10(美元)。
  2. 金钱宝石将其转换为1000(美分)
  3. 我编辑相同的记录,表单预先填充金额字段为1000
  4. 如果我保存记录而不更改任何内容,则会将1000(美元)转换为100000(美分)
  5. 如何以美元而不是美分显示预先填充的金额?

    编辑:

    我尝试像这样编辑_form.html:

    = f.text_field(:amount, :to_money)
    

    我收到此错误:

    undefined method `merge' for :to_money:Symbol
    

4 个答案:

答案 0 :(得分:11)

鉴于迁移如下:

class CreateItems < ActiveRecord::Migration
  def self.up
    create_table :items do |t|
      t.integer :cents
      t.string :currency
      t.timestamps
    end
  end

  def self.down
    drop_table :items
  end
end

一个模型如下:

class Item < ActiveRecord::Base
  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 conver #{value.class} to Money") }
end

然后这个表单代码应该完美运行(我刚刚在Rails 3.0.3下测试),每次保存/编辑时正确显示和保存美元金额。 (这是使用默认的脚手架更新/创建方法)。

<%= form_for(@item) do |f| %>
  <div class="field">
    <%= f.label :amount %><br />
    <%= f.text_field :amount %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

答案 1 :(得分:3)

如果您的表中有多个货币字段,并且您无法将它们全部命名为“分”。

class CreateItems < ActiveRecord::Migration
  def self.up
    create_table :items do |t|
      t.integer :purchase_price_cents
      t.string :currency
      t.timestamps
    end
  end

  def self.down
    drop_table :items
  end
end

将您的模型更改为

class Item < ActiveRecord::Base

  composed_of :purchase_price,
    :class_name  => "Money",
    :mapping     => [%w(purchase_price_cents cents), %w(currency currency_as_string)],
    :constructor => Proc.new { |purchase_price_cents, currency| Money.new(purchase_price_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

答案 2 :(得分:3)

您现在可以直接编辑货币化的字段(money-rails 1.3.0):

# add migration
add_column :products, :price, :price_cents

# set monetize for this field inside the model
class Product
  monetize :price_cents
end

# inside form use .price instead of .price_cents method
f.text_field :price

请参阅https://stackoverflow.com/a/30763084/46039

答案 3 :(得分:0)

简单的货币化方法,步骤如下:

  1. 迁移

add_monetize:table,:amount

  1. 带有验证的模型

获利:amount_cents,allow_nil:true,数值:{greater_than:0}

  1. 控制器许可参数(此处请勿使用amount_cents)

params.require(:model).permit(:amount)

  1. 简单表单输入

保存时,它将以美分保存在db的amount_cents列中