4

Context: On Rails 5.1 the default for Primary Keys changed from Int to BigInt (PR > https://github.com/rails/rails/pull/26266).

I am working on a new Rails 5.1 app which reuses some models from another Rails 4.0 app.

When I run the specs, I have a script that basically loads the Rails 4.0 app's schema.rb from its repo, to create a temp database, so I can use those "external" models (from that other DB) when running tests.

The issue is that given the other app created the schema.rb file on Rails 4.0, all Foreign Keys are integers.

The Rails 4.0 schema file looks like this:

create_table "companies", force: :cascade do |t|
    t.string   "name"
end

create_table "users", force: :cascade do |t|
    t.string   "name",
    t.integer  "company_id", limit: 4, null: false
end

add_foreign_key "users", "companies"

Therefore, when I run tests on the new Rails 5.1 app, it loads that other app schema (the one added above), but when creating the Companies table, it sets the Primary Key as BigInt instead of integer. But the Foreign Key is an integer.

That mismatch is messing up with MySQL:

ActiveRecord::MismatchedForeignKey: Column company_id on table users has a type of int(11). This does not match column id on companies, which has type bigint(20). To resolve this issue, change the type of the company_id column on users to be :integer. (For example t.integer company_id).

I know I could just change all Foreign Keys from that schema to be a BigInt. But I want to try avoiding that solution, given there are quite a lot of Foreign Keys, and in multiple DBs.

Any ideas on how to solve this issue? Or any thoughts?

ascherman
  • 1,762
  • 2
  • 20
  • 41

2 Answers2

0

You can specify an integer type for the primary key for the new table; see this answer. That would give you the opportunity to migrate to bigint primary keys without being rushed into it.

Tom Copeland
  • 1,221
  • 10
  • 10
0

You can specify the type as integer, for example:

t.references :company, type: :integer, foreign_key: true, null: false
Seralto
  • 1,016
  • 1
  • 16
  • 30