Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails4 migration- adding null: false to an add_reference method?

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.

like image 610
L457 Avatar asked Aug 31 '15 07:08

L457


People also ask

What is null false in rails migration?

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.

How can I check my rails migration status?

To check for status, run rails db:migrate:status .

Is null false Ruby?

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.

How do I add a foreign key in Ruby on Rails?

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.


1 Answers

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
like image 117
Johnny Dương Avatar answered Nov 07 '22 21:11

Johnny Dương