2.7.2 :004 > Author.find(1).delete Author Load (0.2ms) SELECT "authors".* FROM "authors" WHERE "authors"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]] Author Destroy (1.0ms) DELETE FROM "authors" WHERE "authors"."id" = ? [["id", 1]] Traceback (most recent call last): ActiveRecord::InvalidForeignKey (SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "authors" WHERE "authors"."id" = ?)
This is the exception i get when i perform delete.
My Author Model Looks like, also used nullify
class Author < ApplicationRecord
has_many :books, dependent: :destroy
end
My Book model looks like this
class Book < ApplicationRecord
belongs_to :author
end
I can destroy the author and the record gets deleted and also destroy the books against that author id, now i want to just delete the author and want the books to remain there or get nullify, but it throws an exception when i delete it
Schema
create_table 'authors', force: :cascade do |t|
t.string 'name'
t.integer 'age'
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
end
create_table 'books', force: :cascade do |t|
t.string 'name'
t.integer 'price'
t.integer 'author_id'
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
t.index ['author_id'], name: 'index_books_on_author_id'
ActiveRecord::InvalidForeignKey (SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "authors" WHERE "authors"."id" = ?)
If you want to be able to nullify author_id you need to create a migration to remove the foreign key and run it:
class RemoveAuthorForeignKeyFromBooks < ActiveRecord::Migration[6.0]
def change
remove_foreign_key :books, :authors
end
end
remove_foreign_key
did not work properly on SQLite before Rails 6 so you may need a workaround on older versions.
class Book < ApplicationRecord
belongs_to :author, optional: true
end
class Author < ApplicationRecord
has_many :books, dependent: :nullify
end
If you don't make the belongs_to relation option then you will not be able to update the book after nullifying the author_id.