简体   繁体   中英

RoR associations: has_one + has_many depedent: :destroy

I don't get why I'm having orphans records when I try to destroy a user. A User has one Cart which has many CartItem


User has one cart:

 class User < ApplicationRecord has_one :cart, dependent: :destroy has_many :cart_items, through: :cart, dependent: :destroy has_many :samples, through: :cart_items, source: :cartable, source_type: 'Sample' has_many :tracks, through: :cart_items, source: :cartable, source_type: 'Track' end 

:dependent

Controls what happens to the associated object when its owner is destroyed:

  • :destroy causes the associated object to also be destroyed

https://apidock.com/rails/v5.2.3/ActiveRecord/Associations/ClassMethods/has_one

Cart has many items:

 class Cart < ApplicationRecord belongs_to :user has_many :cart_items, dependent: :destroy has_many :samples, through: :cart_items, source: :cartable, source_type: 'Sample' has_many :tracks, through: :cart_items, source: :cartable, source_type: 'Track' end 

:dependent

Controls what happens to the associated objects when their owner is destroyed. Note that these are implemented as callbacks, and Rails executes callbacks in order. Therefore, other similar callbacks may affect the :dependent behavior, and the :dependent behavior may affect other callbacks.

  • :destroy causes all the associated objects to also be destroyed.

https://apidock.com/rails/v5.2.3/ActiveRecord/Associations/ClassMethods/has_many

And items:

 class CartItem < ApplicationRecord belongs_to :cart belongs_to :cartable, polymorphic: true end 


I'd like to be able to destroy a User with for example User.last.destroy , but instead I've an error:

 ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: update or delete on table "users" violates foreign key constraint "fk_rails_ea59a35211" on table "carts" DETAIL: Key (id)=(227) is still referenced from table "carts". 

I was thinking that has_one :cart, dependent: :destroy would do the job but it looks like I'm wrong. What am I missing ?

Thanks for your time

I was facing this problem on my development machine, then I found root cause of this issue after lot of debugging and analysis. Postgres was creating extra constraints which was causing this. You need to drop the constraints. You can do this by a migration.

rails g migration remove_fk_constraints

class RemoveFkConstrains < ActiveRecord::Migration[5.2]
  def up
    execute "ALTER TABLE carts DROP CONSTRAINT fk_rails_ea59a35211;"
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM