You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails中为Records表添加基于School_id的Admission_id唯一约束

实现方案

1. 模型层唯一性校验(用于返回友好业务提示)

在Record模型中增加范围唯一性校验规则,指定以school_id为判断范围:

class Record < ActiveRecord::Base
  belongs_to :school
  validates :admission_id, uniqueness: { scope: :school_id }
end

注意:仅靠模型层校验无法完全避免高并发场景下的重复插入问题,必须同时补充数据库层的唯一索引作为最后防线。

2. 数据库层唯一索引(彻底避免重复数据)

首先生成迁移文件:
执行命令 rails generate migration AddUniqueIndexToRecordsOnSchoolIdAndAdmissionId

编辑生成的迁移文件内容:

class AddUniqueIndexToRecordsOnSchoolIdAndAdmissionId < ActiveRecord::Migration[7.0]
  def change
    add_index :records, [:school_id, :admission_id], unique: true
  end
end

执行迁移生效:rails db:migrate

内容的提问来源于stack exchange,提问作者jegan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:06:08