Rails: violates foreign key constraint

前端 未结 2 664
清歌不尽
清歌不尽 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:01

    Try this:

    ActiveRecord::Base.connection.disable_referential_integrity do
        Book.destroy_all
        Genre.destroy_all
        # ...create data 
    end
    
    0 讨论(0)
  • 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
    )
    
    0 讨论(0)
提交回复
热议问题