【问题标题】:How to delete Active Record object with a foreign key without using cascading deletes?如何在不使用级联删除的情况下使用外键删除 Active Record 对象?
【发布时间】:2017-06-13 10:50:16
【问题描述】:

我有两个模型,LaserSheetItem,它们通过 has_many 关系相互关联:

class LaserSheet < ActiveRecord::Base
  belongs_to :job
  has_many :items
  ...
end

class Item < ActiveRecord::Base
  belongs_to :job
  has_many :laser_sheets
  ...
end

因为它们具有多对多关系,所以我希望能够删除 Item 而不删除其关联的 LaserSheets,并且类似地删除 LaserSheet 而不删除其关联的 Items。但是,当我尝试删除其中一个对象时,会出现外键错误:

ERROR: update or delete on table "items" violates foreign key constraint "fk_rails_f7f551ebf9" on table "laser_sheets" DETAIL: Key (id)=(293) is still referenced from table "laser_sheets".

编辑:

在两个模型之间添加引用的数据库迁移:

class AddItemRefToLaserSheets < ActiveRecord::Migration
  def change
    add_reference :laser_sheets, :item
  end
end

class AddLaserSheetRefToItems < ActiveRecord::Migration
  def change
    add_reference :items, :laser_sheet
  end
end

【问题讨论】:

  • 而不是has_many关系,应该是has_and_belongs_to_many吗?
  • 是的,看起来has_and_belongs_to_many 会更合适。

标签: ruby-on-rails database postgresql activerecord foreign-keys


【解决方案1】:

查看dependent options。你可能想要这样的东西:

class LaserSheet < ActiveRecord::Base
  has_many :items, dependent: :nullify
  ...

class Item < ActiveRecord::Base
  has_many :laser_sheets, dependent: :nullify
  ...

【讨论】:

    猜你喜欢
    • 2012-09-18
    • 2011-05-06
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    相关资源
    最近更新 更多