2012-12-11 72 views
4

我使用活動管理與money - https://github.com/RubyMoney/money寶石。我有一些由金錢寶石處理的屬性。活躍的管理員和金錢

金錢寶石的價值以美分計。當我使用活動管理員創建一個條目時,在數據庫中創建正確的值(5000爲50.00)。

但是,當我編輯一個條目,該值乘以100,這意味着AA顯示5000原始輸入50.00。如果我用金錢屬性編輯任何東西,它會乘以100.在創建時,價值通過貨幣邏輯,但在版本中,不知何故活躍的管理員跳過該部分顯示美分而不是最終的貨幣價值。 有沒有辦法使用活躍管理員的錢寶石?

例如:

form :html => { :enctype => "multipart/form-data"} do |f| 
    f.inputs "Products" do 
    ...... 
    f.has_many :pricings do |p| 
     p.input :price 
     p.input :_destroy, :as => :boolean,:label=>"Effacer" 
    end 
    f.actions :publish 
end 

型號:

# encoding: utf-8 
class Pricing < ActiveRecord::Base 
belongs_to :priceable, :polymorphic => true 
attr_accessible :price 
composed_of :price, 
    :class_name => "Money", 
    :mapping => [%w(price 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 
+2

你能提供鏈接到錢寶石 https://github.com/collectiveidea/money或https://github.com/RubyMoney/money? 也看到你的模型的源代碼會很好 – Fivell

回答

0

我的問題,從我的錢的用法傳來:

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

我改名爲我的價格在DB通過price_cents,我把它在它需要的類貨幣宣言。我在使用分利,我應該使用價格,即使如此,使用相同的名稱在數據庫中的金錢對象和字段似乎並沒有工作。最後,問題與Active Admin無關。

1

Rails callbacks是創建一個解決這種問題非常方便。

我只會使用和after_update回調。

例子:

# encoding: utf-8 
    class Pricing < ActiveRecord::Base 
    after_update :fix_price 
    belongs_to :priceable, :polymorphic => true 
    attr_accessible :price 
    composed_of :price, 
     :class_name => "Money", 
     :mapping => [%w(price 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") } 

    def fix_price 
    self.price = (self.price/100) 
    end 
    end