0

Bigint columns in models with values like 1456299399553483799 get converted to things like 1456299399553483800 when run through as_json.

Is there an easy/ built-in way to have the numbers converted to strings when serializing a bigint to avoid truncation?

Michael Wasser
  • 1,776
  • 2
  • 21
  • 32

1 Answers1

0

One possible solution -- I added the following code as an initializer:

# config/initializers/bigint_serializer.rb

class Integer
  def as_json(options = nil)
    self > 2147483647 ? self.to_s : self
  end
end

This overrides the default behavior of Numeric#as_json from https://github.com/rails/rails/blob/v5.1.4/activesupport/lib/active_support/core_ext/object/json.rb#L95 and results in numbers bigger than a 4-byte signed max int being turned into a string.

Note, I'm pretty sure you'd actually be ok with a bigger int value before switching to a string -- perhaps 9007199254740991 but I left it as max 4-byte int as I didn't need smaller ints being ints (see What is JavaScript's highest integer value that a Number can go to without losing precision?)

Michael Wasser
  • 1,776
  • 2
  • 21
  • 32