can't delete object due to foreign key constraint

后端 未结 2 508
太阳男子
太阳男子 2020-12-03 13:38

I\'m trying to do a simple user.destroy but running into the following error:

ERROR: update or delete on table \"users\" violates foreig

相关标签:
2条回答
  • 2020-12-03 14:13

    An easy solution is to simply cascade-delete the records in the associated table, which can be done through active record, like so:

    user.rb

    class User < ActiveRecord::Base
      has_many :identities, dependent: :destroy
    
      # rest of user class
    end
    

    Check out the documentation pertaining to has_many for more info.

    0 讨论(0)
  • 2020-12-03 14:19

    You would need to remove the Identity that references the user first. Then you can delete the user.. By default the foreign key is doing a restrict so you cannot delete the user if anything references to it.

    if you would like use Rails to handle destroying the identity you can do

    class User < ActiveRecord::Base
      has_many :identities,  dependent: :destroy 
    
      ......
    
     end 
    

    Which would cause Rails to destroy all the dependent records.

    But as you are using Foreign keys, you can adjust your migration to set cascade deletes

     add_foreign_key :identities, :users, on_delete: :cascade
    

    Assuming rails 4.2 which has native support

    0 讨论(0)
提交回复
热议问题