Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 Migration Data Type Issue

I originally developed my rails 5 application using PostgreSQL. I had to change over to a MariaDB after I had done all of my development due to some issues with hosting.

I'm trying to put in an update that adds a reference to the admin from my shopping cart. Here is my migration:

class AddAdminRefToCart < ActiveRecord::Migration[5.1]
  def change
    add_reference :carts, :admin, foreign_key: true
  end
end

when I run

rake db:migrate

I get this error:

== 20171129152942 AddAdminRefToCart: migrating ================================
-- add_reference(:carts, :admin, {:foreign_key=>true})
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

Column `admin_id` on table `carts` has a type of `bigint(20)`.
This does not match column `id` on `admins`, which has type `int(11)`.
To resolve this issue, change the type of the `admin_id` column on `carts` to be :integer. (For example `t.integer admin_id`).

The error makes sense but I am unsure of the proper way to fix the issue. Can someone please give some guidance on how I should write my migration? Thanks in advance!

like image 597
Cannon Moyer Avatar asked Sep 10 '26 10:09

Cannon Moyer


1 Answers

You can just specify the exact data type you want, instead of using add_reference.

add_column :carts, :admin_id, :integer, limit: 4
add_foreign_key :carts, :admins

The limit: 4 parameter is telling the database to create a 4-byte field, which would correspond to INT, as opposed to limit: 8 (apparently the default now), which would correspond to BIGINT.

As I mentioned in the comments, this will not create any issues by not using add_reference, since add_reference is just "syntactic sugar" for add_column and, optionally, add_index and add_foreign_key.

like image 127
jeffdill2 Avatar answered Sep 12 '26 05:09

jeffdill2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!