2011-01-31 80 views
8

我遇到了表單和money gem問題。Rails錢寶石和表單生成器

這是我的問題:

  1. 我創造出具有「數量」字段(映射到錢的對象)的記錄。假設我輸入10(美元)。
  2. 錢寶石將其轉換爲1000(美分)
  3. 我編輯同一記錄和形式的預填充量字段1000
  4. 如果我保存記錄不改變任何東西,它會轉換成1000(美元)至100000(美分)

如何使其顯示以美元而不是美分計算的預填充金額?

編輯:

我試圖編輯這樣的_form.html:

= f.text_field(:amount, :to_money) 

,我得到這個錯誤:

undefined method `merge' for :to_money:Symbol 
+0

這是1345 。我認爲這個表格正在檢索存儲的值,而不會將其轉換回美元。 – David 2011-01-31 23:36:52

+0

那麼如何將1000轉換爲100而不是顯示1,000?!有什麼地方錯了。其次(我沒有使用金錢寶石),但我懷疑數量字段的屬性閱讀器不會轉換該值。或者,也許這需要你做,而不是寶石?你發佈的一些代碼將有所幫助。另外,請檢查已加載的記錄並查看金額字段的值。 – Zabba 2011-01-31 23:40:20

+0

對不起,這是一個錯字。它預先填充爲1000. – David 2011-02-01 00:09:31

回答

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 

和一個模型作爲fol低點:

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 %> 
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 
3

現在,您可以直接編輯貨幣化領域(錢軌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