Rails: violates foreign key constraint
Add dependent: :destroy
option to your has_many
definitions.
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)
Try this:
ActiveRecord::Base.connection.disable_referential_integrity do Book.destroy_all Genre.destroy_all # ...create data end