Rails rails-money undefined method `cents'

Rails rails-money undefined method `cents'

我正在尝试实施 money-rails,但 运行 出现以下错误:

undefined method `cents' for "1,000.00":String

我跟随 this tutorial 获得了一个 "fancy" 货币输入字段。

数据库模式:

t.integer  "balance_cents",    default: 0,     null: false
t.string   "balance_currency", default: "USD", null: false

型号:

monetize :balance_cents, as: :balance, allow_nil: :true, :numericality => { :greater_than_or_equal_to => 0}

def initialize(attributes = {})
  super
  @balance = attributes[:balance]
end

表格:

<%= form_for(@asset, url: assets_new_path) do |f| %>
  <%= f.label :balance, "Balance / Value ($)" %>
  <%= f.number_field :balance, data: { role: 'money', a_sep: ',', a_dec: '.' }, class: 'form-control' %>

控制器:

def create
  @asset = Asset.new(asset_params)
  if @asset.save
    flash[:success] = "New asset created successfully."
    redirect_to assets_path
  else
    ...
  end
end

def asset_params
  params.require(:asset).permit(:balance)
end

我是否应该以另一种(更好的)方式设置 :balance 输入字段?

根据 Rails Guidesafter_initialize 回调中执行此操作的最佳方法。

为您的列使用 balance_satangs 而不是 balance_cents