• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

746
Views
I have created a association in rails on a author(has_many) and book(belongs_to), Now upon deleting the author(dependent: :destroy), i get exeception

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

about 3 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error