4

我正在使用有钱的活跃管理员 - https://github.com/RubyMoney/money gem。我有一些由金钱宝石处理的属性。

金钱宝石以美分存储价值。当我使用活动管理员创建条目时,会在 DB 中创建正确的值(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
4

2 回答 2

1

Rails 回调对于创建此类问题的解决方案非常方便。

我只会使用 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
于 2013-01-30T16:59:39.463 回答
0

我的问题来自我对 Money 的使用:

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 无关。

于 2013-02-10T17:45:17.350 回答