我有两个模型,LaserSheet
和Item
,彼此之间有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
答案 0 :(得分:3)
查看dependent options。你可能想要这样的东西:
class LaserSheet < ActiveRecord::Base
has_many :items, dependent: :nullify
...
class Item < ActiveRecord::Base
has_many :laser_sheets, dependent: :nullify
...