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