[英]RoR associations: has_one + has_many depedent: :destroy
当我尝试销毁用户时,我不明白为什么会有孤儿记录。 用户 具有其中有许多 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
:依赖
控制当关联对象的所有者被销毁时会发生什么情况:
- :destroy导致关联的对象也被破坏
https://apidock.com/rails/v5.2.3/ActiveRecord/Associations/ClassMethods/has_one
购物车有很多物品:
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按顺序执行回调。 因此,其他类似的回调可能会影响:depend行为,而:dependent行为可能会影响其他回调。
- :destroy导致所有关联的对象也被破坏。
https://apidock.com/rails/v5.2.3/ActiveRecord/Associations/ClassMethods/has_many
和项目:
class CartItem < ApplicationRecord belongs_to :cart belongs_to :cartable, polymorphic: true end
User.last.destroy
销毁一个User,但是却出现了一个错误:
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
可以完成这项工作,但看起来我错了。 我想念什么?
谢谢你的时间
我在开发机器上遇到了这个问题,然后经过大量的调试和分析,我发现了这个问题的根本原因。 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
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.