【发布时间】:2016-04-22 08:21:16
【问题描述】:
我在两个表之间建立了一个关联表,如下所示:
class Patient
has_and_belongs_to_many :doctors
end
class Doctor
has_and_belongs_to_many :patients
end
# join table for patients_doctors
class CreatePatientDoctors < ActiveRecord::Migration
def change
create_table :patients_doctors, :id => false do |t|
t.references :patient, :null => false
t.references :doctor, :null => false
end
add_index :patients_doctors, [:patient_id, :doctor_id]
end
end
我想要一个条件,使得a patient should consult a doctor 只出现一次。 (这只是一个例子,因为我不能在这里分享我客户的代码)
截至目前,当我尝试保存 duplicate entry 时,它会在日志中显示 database level constraint error,如下所示:
ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_uniqueness"
DETAIL: Key (patient_id, doctor_id)=(16, 1) already exists.
我想使用validation 以获得更好的控制和可用性因素。
我尝试将validates_associated 用于Doctor 类
# in patient class
validates :doctors, uniqueness: true
validates_associated :doctors
但我仍然得到相同的database constraint error。请建议我哪里做错了。
【问题讨论】:
标签: ruby-on-rails postgresql validation ruby-on-rails-4