Ziggurat
Ziggurat

Reputation: 257

Ruby on Rails mapping a BigDecimal field of existing table

I created a rails model class for an existing table. Some of the table fields are decimal fields defined in the Postgres DB as numeric(19,2). When I open the rails console and fetch one of this objects like this:

 ExistingTableModel.first.total
 #<BigDecimal:4bfd250,'0.692E3',9(18)>

So, I am getting a BigDecimal 9(18) . This is a problem because when I do sums and stuff like that, the results are not nice due to rounding.

How can I force rails to map those fields to a BigDecimal with 2 decimals?

Thanks!

Upvotes: 1

Views: 569

Answers (2)

RadBrad
RadBrad

Reputation: 7304

You could override attribute accessor(s). Say you have a legacy Postgres table with an attribute foo numeric(19,2)

model ExistingTableModel < ActiveRecord::Base
  def foo
    read_attribute(:foo).round(2)
  end
end

This would make every access of the foo attribute rounded to precision of 2 decimal places.

Upvotes: 2

Daniel Szmulewicz
Daniel Szmulewicz

Reputation: 3961

Use the precision and scale options in the relevant table column of your model.

From the docs:

The precision is the number of significant digits, while the scale is the number of digits that can be stored following the decimal point. For example, the number 123.45 has a precision of 5 and a scale of 2. A decimal with a precision of 5 and a scale of 2 can range from -999.99 to 999.99.

PostgreSQL: :precision [1..infinity], :scale [0..infinity]. No default.

Full API reference

Upvotes: 1

Related Questions