s1gtrap
s1gtrap

Reputation: 150

Ruby on Rails ignoring integer limit

I need to index a table of users using an externally sourced id, which is a 64-bit integer. Rails is perfectly capable of storing such a number, unless it's the primary key it seems. I have the following migration:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users, :id => false do |t|
      t.integer :id, limit: 8
      t.string :name

      t.timestamps null: false
    end
  end
end

The migration works fine, no errors reported, but when I attempt to seed it with a 64-bit integer, I'm told off by this:

RangeError: 76561198054432981 is out of range for ActiveRecord::Type::Integer with limit 4

Obviously Rails is ignoring the limit field, so long as it's the primary key/the :id field? How should I go about dealing with this?

For what it's worth I'm using sqlite3 (default), but to my knowledge, sqlite is perfectly capable of storing 64-bit integers.

Here's the table_info from sqlite:

0|id|integer(8)|0||0
1|name|varchar|0||0
2|created_at|datetime|1||0
3|updated_at|datetime|1||0

Upvotes: 6

Views: 4864

Answers (1)

Shiva
Shiva

Reputation: 12514

The limit value you gave is correct; it corresponds to BIGINT type enter image description here Make sure your migration is applied; open you database in some CLI or GUI software and verify the col-type

Addition: Changing a column's length or datatype in a migration will invalidate the column as a primary key. Rather, creating an initializer that overrides the site's default primary key datatype should provide the behavior you're looking to implement:

# config/initializers/change_primary_key_datatype.rb
require 'active_record/connection_adapters/postgresql_adapter'
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::NATIVE_DATABASE_TYPES[:primary_key] = "bigserial primary key"

This is what we would do for PG database; This is possible because of

enter image description here


however in the code base of SQLite there is

enter image description here

Upvotes: 4

Related Questions