10

フォームとmoney gemに問題があります。

これは私の問題です:

  1. 「金額」フィールドを持つレコードを作成します (money オブジェクトにマップされます)。10 (ドル) を入力するとします。
  2. マネー ジェムはそれを 1000 (セント) に変換します。
  3. 同じレコードを編集すると、フォームの金額フィールドに 1000 が事前入力されます
  4. 何も変更せずにレコードを保存すると、1000 (ドル) が 100000 (セント) に変換されます。

事前入力された金額をセントではなくドルで表示するにはどうすればよいですか?

編集:

_form.html を次のように編集してみました。

= f.text_field(:amount, :to_money)

そして、私はこのエラーを受け取ります:

undefined method `merge' for :to_money:Symbol
4

4 に答える 4

12

次のような移行が考えられます。

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 でテストしたところです)、保存/編集するたびに金額が適切に表示および保存されます。(これは、デフォルトの scaffold update/create メソッドを使用しています)。

<%= form_for(@item) do |f| %>
  <div class="field">
    <%= f.label :amount %><br />
    <%= f.text_field :amount %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
于 2011-02-01T01:49:14.303 に答える
3

テーブルに複数の金額フィールドがあり、それらすべてに「cents」という名前を付けることができない場合。

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
于 2011-04-15T20:46:45.153 に答える
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を参照してください

于 2015-12-15T00:51:03.477 に答える