我目前在运行时遇到此错误
Shop.last.destroy
,但我不明白为什么:
PG::ForeignKeyViolation: ERROR: update or delete on table "credit_changes" violates foreign key constraint "fk_rails_16918229d0" on table "sms_historicals" (ActiveRecord::InvalidForeignKey)
这是一个 Postgres 数据库
我的模型看起来像这样:
class SmsHistorical < ApplicationRecord
belongs_to :customer
belongs_to :credit_change, optional: true
belongs_to :notification_setting, optional: true
end
class CreditChange < ActiveRecord::Base
belongs_to :credit
belongs_to :customer
has_one :sms_historicals
has_one :email_historicals
end
创建这些表的迁移如下:
create_table :credit_changes, if_not_exists: true do |t|
t.integer "credit_id"
t.text "credit_notes"
t.decimal "credit_amount_changed", precision: 4, scale: 2, default: 0.0
t.datetime "date"
t.string "transaction_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
class CreateSmsHistoricals < ActiveRecord::Migration[6.1]
def change
create_table :sms_historicals, if_not_exists: true do |t|
t.string :phone_number
t.text :message
t.references :customer, null: true, foreign_key: true, on_delete: :cascade
t.references :credit_change, null: true, foreign_key: true, on_delete: :cascade
t.references :notification_setting, null: true, foreign_key: true, on_delete: :cascade
t.timestamps
end
end
end
belongs_to :credit_change
是 Sms 和 Credit 表之间的 FK。 Credit ID 存储在Sms 表中。当您尝试删除Credit时,还需要清除Sms表中的数据。例如
class CreditChange < ActiveRecord::Base
has_one :sms_historicals, dependent: :nullify
end
我在这里选择
:nullify
,因为您在短信表上将belongs_to :credit_change
设置为可选。但也可以是其他东西:https://guides.rubyonrails.org/association_basics.html#options-for-has-one