我有两个模型,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".编辑:
DB迁移在这两种模型之间添加参考资料:
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发布于 2017-01-28 01:35:51
看看相依期权。你可能想要这样的东西:
class LaserSheet < ActiveRecord::Base
has_many :items, dependent: :nullify
...
class Item < ActiveRecord::Base
has_many :laser_sheets, dependent: :nullify
...https://stackoverflow.com/questions/41899335
复制相似问题