Rails: violates foreign key constraint

前端 未结 2 663
清歌不尽
清歌不尽 2021-01-04 23:54

I have three models: Book, genre, BookGenre, and here are relationships:

class BookGenre < ActiveRecord::Base
  bel         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 00:12

    Add dependent: :destroy option to your has_many definitions.

    Check docs

    Yet better option to respect data integrity is to set the CASCADE DELETE on the database level: say, you have comments table and users table. User has many comments You want to add a foreign_key to table comments and set deleting the comment whenever the user is destroyed you would go with the following (the on_delete: :cascade option will ensure it):

    add_foreign_key(
      :comments,
      :users,
      column:
      :user_id,
      on_delete: :cascade
    )
    

提交回复
热议问题