medBouzid
medBouzid

Reputation: 8382

rails 6 foreign key can't be null

I have a migration file as the following:

def change
    create_table :carts do |t|
      t.string :order_number
      t.decimal :total_price
      t.bigint :user_id, null: true
      t.string :status

      t.timestamps
    end
  end

I want to allow the user_id to be null, but my schema file translate this migration to:

t.bigint "user_id", null: false

So in my cart.rb model even if I have

belongs_to :user, optional: true

it doesn't work and when I try to save a cart object I get the ForeignKey can't be null error !

How I can allow null value for a foreign key ?

Upvotes: 1

Views: 2298

Answers (1)

Vasfed
Vasfed

Reputation: 18454

Migrations are not a declaration of current db structure, they are changes that when combined - produce it. For combined structure rails have db/schema.rb (or schema.sql for more complex scenarios)

If the column is null: false then it must have been changed by some later migration (or directly in db, if so - db structure may be out of sync between development and production). If you want it again to be null: true - add another migration that will change that. But first I'd figure out why it ended up in current state, may be there's a reason.

change_column :carts, :user_id, :bigint, null:true

Upvotes: 1

Related Questions