I've just started learning rails so sorry if the answer to this if fairly obvious.
I've added migrations for posts and categories tables in my app and am now adding a reference to categories in my posts table with a default value of not null using the following line:
add_reference :posts, :category, index: true, foreign_key: true, null: false
however I get the following error on running the migration:
SQLite3::SQLException: Cannot add a NOT NULL column with default value NULL: ALTER TABLE "posts" ADD "category_id" integer NOT NULL
I've tried reading through the api, but couldn't figure out what I am doing wrong.
The null: false parameter means this column does not allow NULL values. The default: false tells us this column will default to false whenever a value isn't specified. This is nice because we can guarantee this field will always be either true or false now. It can't be null because the database prevents it.
To check for status, run rails db:migrate:status .
Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement.
If you want you can always use add_index on the fields that you want as foreign keys. Or you can write your migrations in SQL or perhaps even force rails to do the foreign keys somehow. But the thing is you won't even look for a way to do it if you don't know rails is not doing itin the first place.
maybe sqlite3 don't allow to do that, try
add_reference :posts, :category, index: true, foreign_key: true, null: false
change_column :posts, :category_id, :integer, null: false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With