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" = ?)