Lee McAlilly
Lee McAlilly

Reputation: 9316

Best way to convert a field in Rails from decimals to integer in cents

I have a Product model in Rails and the amount is stored as an integer in cents in the database.

Example of this field:

enter image description here

It seems like the Money gem might be overkill for this. Surely this is a common problem. What is a common way people solve this?

Upvotes: 1

Views: 550

Answers (1)

mechnicov
mechnicov

Reputation: 15248

Just as ideas

Using money gem

class Product < ApplicationRecord
  monetize :price_cents
end
= f.input :price

Or using monkeypatching

class Product < ApplicationRecord
  def price
    self[:price] / 100.0
  end

  def price=(value)
    super(value * 100)
  end
end

In my opinion gem is more convenient

Upvotes: 4

Related Questions