3

I have Integer attribute in my model and I need back-end validation for that (it should be up to 7 digts only). In my model I do some validations like:

validates :duration, format: { with: /([0-9]{1,7})/ }
validates :duration, numericality: { less_than_or_equal_to: 9999999 }

This works when I try to put letters into the form (it returns 'is not a number' error), works well when I put valid integer (11045555 - returns 'must be less than or equal to 9999999') BUT it crashes when I put really big number - let's say 11045555766666666666. Error is "11045555766666666666 is out of range for ActiveRecord::Type::Integer with limit 4"

How can I skip this crash when user puts that big number?

I use mysql2 DB.

alv_721
  • 305
  • 3
  • 18
  • Try update rails, it's fixed - [similar problem](http://stackoverflow.com/questions/28095568/rangeerror-for-simple-integer-assignment-in-rails-4-2-0-that-should-be-caught-by#answer-28120052) – Fist Feb 27 '15 at 09:29

1 Answers1

4

You have to declare the limit on your migration file. By default, an integer is coded in 4 bytes, so the limit is 2147483647.

If you want to set a bigger limit, declare it like this

add_column :yourtable, :duration, :integer, :limit => 8

8 bytes have a 9223372036854775807 limit.

Just check How to specify the size of an integer in the migration script

Community
  • 1
  • 1
pierallard
  • 3,326
  • 3
  • 21
  • 48
  • 1
    This is not a good approach as it just raises the size of the field stored in the database. He clearly wont actually be storing large numbers in his database and so he should not have to increase the integer size there. I am facing the same issue and do not wish to increase to a int(8) just to work around this bug. – Brad Aug 16 '18 at 01:33