0

I am using the Money gem and composed_of as per this answer: https://stackoverflow.com/a/3843805/4162458

I have an integer column in my database, :discount

product.rb

  class Product < ActiveRecord::Base

    composed_of :discount_display,
      :class_name => 'Money',
      :mapping => %w(discount cents),
      :converter => Proc.new { |value| Money.new(value) }

And in my form:

<%= f.number_field :discount_display, class: 'form-control', min: "0" %>

However, if I enter 12, it saves in the database as 12 and displays on the form when I refresh as 0.12.

How can I have it so that when you enter "12" it is saved as 1200 in the db and displays properly, as that answers seems to say should happen?

Community
  • 1
  • 1
aquint
  • 512
  • 3
  • 14
  • Take a look at the [money-rails](https://github.com/RubyMoney/money-rails) gem, it handles the conversion for you. – Stefan Oct 13 '16 at 16:42

1 Answers1

1

As per documentation,

Represents monetary values as integers, in cents. This avoids floating point rounding errors.

Hence, if you expect collect dollars from the user, then, you need to convert it to cents before saving in DB. Perhaps, your converter proc should be

Proc.new { |value| Money.new(value * 100) }

or

Proc.new { |value| Money.from_amount(value, "USD") }
Wand Maker
  • 18,476
  • 8
  • 53
  • 87