Search code examples
ruby-on-railsmoney-rails

Rails rails-money undefined method `cents'


I am attempting to implement money-rails and I have run into the following error:

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

I followed this tutorial to get a "fancy" currency input field.

DB schema:

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

Model:

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

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

Form:

<%= 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' %>

Controller:

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

Should I be setting up the :balance input field another (better) way?


Solution

  • According to the Rails Guides the best way to do it in the after_initialize callback.