Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

886
Visualizações
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" = ?)

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda