Home > OS >  The Destroy file erre in rails during the relational RDBMS Sysstem
The Destroy file erre in rails during the relational RDBMS Sysstem

Time:06-29

def destroyBook
    @book = Book.find(params[:id])
    @book.destroy
    Book.find_by(id:params[:id]).book_authors.destroy_all
    Book.find_by(id:params[:id]).book_categories.destroy_all 
    @book = Book.all 
    redirect_to "/books/views"
end

error Shows on display

it will be working or rails console

CodePudding user response:

You can't find the book record after you deleted it. If you want to destroy has_many relation records you must destroy them first. The reason you don't encounter this error on console is because when you call and assign the book record in a variable you can reach that object even after you destroy it from database. Because the book objaect has written in the memory.

Also there is a proper way to achive what you want in model using dependent: :destroy option. For example:

has_many :book_authors, dependent: :destroy

If you define has_many relation like this then book_authors record that belongs to book will always be destroyed when you destroy the book.

  • Related