Rails 有很多通过自我独特的验证

Rails has many through self unique validation

我有两个模型,用户和教练

一个用户可以有多个学生和教练

来自用户模型的代码:

  has_many :coachings, :foreign_key => :student_id
  has_many :coaches, :through => :coachings, :foreign_key => :coach_id

Coachings 模型中的代码:

belongs_to :coach, :class_name => 'User'
belongs_to :student, :class_name => 'User'

但这允许将重复记录添加到数据库(一个用户可以有重复的教练或重复的学生)。如何正确验证这一点?

谢谢

看来您正在寻找一种方法来验证 coach_idstudent_id 组合的唯一性。

试试这个:

coaching.rb

validates_uniqueness_of :coach_id, scope: :student_id