【问题标题】:How to use validates_associated for join table in rails 4如何在 Rails 4 中使用 validates_associated 连接表
【发布时间】: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


    【解决方案1】:

    您需要在 PatientDoctor 模型中验证 patient_id 和 doctor_id 的组合是唯一的。您可以使用范围来执行此操作,您可以列出属性以限制唯一性检查:

    validates :patient_id, uniqueness: { scope: :doctor_id }
    

    validates_associated 确保关联的记录是有效的。它不检查关联的唯一性。

    【讨论】:

    • 我没有 PatientDoctor 模型,因为关联是 HABTM
    • 其实[patient_id , doctor_id]的组合应该是唯一的。
    • 我猜你应该把关联改成has_many through关联。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    相关资源
    最近更新 更多