我有一个has_many
评论的post
ActiveRecord模型,但我忘了在声明它时添加:dependent => :destroy
。现在我有几个带评论的帖子,我不能删除它们,因为我得到这个错误:
PG::ForeignKeyViolation: ERROR: update or delete on table "posts" violates foreign key constraint "fk_rails_c9b8ba77e9" on table "comments"
DETAIL: Key (id)=(2) is still referenced from table "comments".
我在事实之后添加了:dependent => :destroy
声明,但我很确定我不能这样做,那么我如何创建一个迁移呢?
我修复了我的问题,像这样:
class UpdateChartForeignKey < ActiveRecord::Migration[7.0]
def change
remove_foreign_key :comments, :posts
add_foreign_key :comments, :posts, on_delete: :cascade
end
end
class User < ApplicationRecord
has_many :posts, dependent: :destroy
end
这将添加:dependent =>:destroy User模型与posts表关联的声明,表明当一个用户被删除时,所有关联的posts也应该被删除。