簡體   English   中英

RoR關聯:has_one + has_many depedent::destroy

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM