我最近在Rails应用程序中发现了与连接表中的重复条目相关的问题。该应用程序是教育性的,包括学生和练习模型。连接表记录了哪些学生分配了哪些练习。将练习多次分配给学生是没有意义的(即不应允许在连接表中使用重复的条目)。
我通过向连接表添加唯一性验证来部分解决了这个问题(请参阅下面的最后一行代码)。此验证将防止将来创建任何新的重复条目。但是,我仍然面临着解决表中现有重复项的问题。
有没有办法针对整个现有数据库运行新验证,以检索不再有效的所有记录?
class Student < ActiveRecord::Base
has_many :student_exercise_assignments
has_many :exercises, :through => :student_exercise_assignments
end
class Exercise < ActiveRecord::Base
has_many :student_exercise_assignments
has_many :students, :through => :student_exercise_assignments
end
class StudentExerciseAssignment < ActiveRecord::Base
belongs_to :student
belongs_to :exercise
validates :exercise_id, :uniqueness => { :scope => :student_id, :message => "An exercise can only be assigned to a student once" }
更新
下面的Shioyama的答案给出了我正在寻找的信息。然而,作为一个Rails新手,我对他在&
中使用&:invalid?
感到有些困惑。如果有人需要Ruby中&
运算符的引子,那就有一个很好的here。
答案 0 :(得分:7)
如何:
invalid_assignments = StudentExerciseAssignment.select(&:invalid?)
这将选择在使用invalid?
方法调用时返回true的所有赋值。然后,您可以做任何您需要做的事情来修复它们。
作为旁注,我还建议为数据库添加唯一性约束。请参阅此答案,原因如下:Rails: Validation in model vs migration