19

I'm trying to save a number representing the length of a file (4825733517). The column is set to type integer. I don't have any validations or restrictions set.

RangeError: 4825733517 is out of range for ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Integer with limit 4

Should I be using some other column type for this value? (on rails 4.2.4)

p4sh4
  • 3,292
  • 1
  • 20
  • 33
Ashbury
  • 2,160
  • 3
  • 27
  • 52

3 Answers3

31

For columns of type integer, the :limit value is the maximum column length in bytes (documentation).

With 4 byte length, the largest signed integer you can store is 2,147,483,647, way smaller than your value of 4,825,733,517. You can increase the byte limit, for example to 8 bytes to be a long integer (a bigint PostgreSQL type), this will allow you to store signed values up to 9,223,372,036,854,775,807.

You can do this with a migration create it with something like rails generate migration change_integer_limit_in_your_table, and the following code:

class ChangeIntegerLimitInYourTable < ActiveRecord::Migration
  def change
    change_column :your_table, :your_column, :integer, limit: 8
  end 
end
p4sh4
  • 3,292
  • 1
  • 20
  • 33
  • 1
    FYI this is a great answer and *almost* worked for me. What **did** work was all the same syntax but `change_column` instead of `update_column`. I'm using Rails 4.2.6 so maybe "update_column" is deprecated. – B. Bulpett Apr 29 '16 at 20:32
  • You are absolutely right - `update_column` is simply incorrect, I might've got a wrong cue from the other answers when first writing this. Edited the post, thanks for pointing it out – p4sh4 May 02 '16 at 11:55
5

According to the PostgreSQL documentation an integer have a range from -2147483648 to +2147483647. So your number is to big for this type.

Update your column and use the parameter limit to indicate that you want to have a bigint.

change_column :table, :column, :integer, limit: 8
Barry
  • 746
  • 9
  • 20
Robin
  • 8,162
  • 7
  • 56
  • 101
0

You should change the length of the column in your database with a migration :

update_column :my_table, :my_column, :integer, limit: 12

It will allow you to store bigger integers.

Caillou
  • 1,451
  • 10
  • 19
  • 12 bytes is completely overkill, and also doesn't correspond to an available numeric type in PostgreSQL. – p4sh4 Nov 04 '15 at 09:17
  • I just put 12 as an example. We don't even know the maximum integer he will need to save. – Caillou Nov 04 '15 at 09:19