我不明白为什么我有孤儿的记录,当我试图摧毁一个用户。用户有一个Cart,它有多个CartItem
用户有一个购物车:
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*受抚养人 控制关联对象在其所有者被销毁时发生的情况:
购物车有许多项目:
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*受抚养人 控制关联对象在其所有者被销毁时发生的情况。请注意,这些是作为回调实现的,Rails按照顺序执行回调。因此,其他类似的回调可能会影响:依赖行为,而:依赖行为可能会影响其他回调。
和项目:
class CartItem < ApplicationRecord
belongs_to :cart
belongs_to :cartable, polymorphic: true
end
我希望能够使用例如User.last.destroy来破坏用户,但是我有一个错误:
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".我原以为has_one :cart, dependent: :destroy会做这份工作,但看来我错了。我错过了什么?
耽误您时间,实在对不起
发布于 2019-07-03 20:40:34
我在我的开发机器上遇到了这个问题,经过大量的调试和分析,我找到了这个问题的根源。Postgres制造了额外的限制,导致了这一切。你需要取消约束。你可以通过迁移来做到这一点。
rails g migration remove_fk_constraints
class RemoveFkConstrains < ActiveRecord::Migration[5.2]
def up
execute "ALTER TABLE carts DROP CONSTRAINT fk_rails_ea59a35211;"
end
endhttps://stackoverflow.com/questions/56875279
复制相似问题