Rails: violates foreign key constraint

旧巷老猫 提交于 2019-11-30 19:07:37

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
)

Try this:

ActiveRecord::Base.connection.disable_referential_integrity do
    Book.destroy_all
    Genre.destroy_all
    # ...create data 
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!