Reputation: 2016
I have a rails model using postgres, with a height_value column, which is set as a decimal.
I want to store values without the trailing zeros, but I am thinking this is not possible with a decimal column type?
If it's not possible to store them this way, what is the best approach to trim off the trailing zeros in my model to make them always display properly. Should I change the column, is there a precision that would do what I want?
so if height_value:
28.5 => 28.5
28.0 => 28
19.75 => 19.75
19.00 => 19
Schema
create_table "buildings", force: true do |t|
t.decimal "height_value"
end
Upvotes: 1
Views: 1036
Reputation: 768
define a read method in your model like this.The value returned will be a string
def height_value
"%g" % read_attribute(:height_value)
end
if you want the method to return a number then
def height_value
val = read_attribute(:height_value)
if val == val.to_i
val.to_i
else
val
end
end
The value stored will be decimal but the value returned from database will satisfy the requirements
Upvotes: 3