1

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
1
  • The numeric type (which I think Rails calls decimal) should behave exactly how you want if it is defined in the database as simple numeric, with no precision or scale set. You may have a challenge getting Rails to it, though. Commented Dec 31, 2013 at 20:24

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. i was close. i had the method with "%g" % height_value, but no read_attribute()
the original answer was causing an issue when i go to create a new record, "can't convert nil into Float"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.