Rails4 migration - adding null: false to add_reference method?

I just started to study the rails, so sorry if the answer to this is pretty obvious.

I have added migrations for posts and categories in my application, and now add a link to the categories in my message table with a default value other than zero using the following line:

add_reference :posts, :category, index: true, foreign_key: true, null: false

however, I get the following error when starting the migration:

SQLite3::SQLException: Cannot add a NOT NULL column with default value NULL: ALTER TABLE "posts" ADD "category_id" integer NOT NULL

I tried reading through the api, but could not understand what I was doing wrong.

+4
source share
4 answers

, , sqlite3. -, , , ( MYSQL). . , create_table .

0

, sqlite3 ,

add_reference :posts, :category, index: true, foreign_key: true, null: false
change_column :posts, :category_id, :integer, null: false
+3

, " ", .

, null: false.

NULL POSTS,

validates :category, presence: true

Post.

See also Also check out this post https://robots.thoughtbot.com/referential-integrity-with-foreign-keys to better understand foreign keys in Rails.

0
source
0
source