【问题标题】:Validating Uniqueness within data in another Table验证另一个表中数据的唯一性
【发布时间】:2015-06-04 14:23:57
【问题描述】:
我有一个 Student 和 Student_section 模型。 Student 表有student_id and roll_no,Student_section 有student_id, standard_id and section_id。
Roll_no 在standard 和section 中应该是唯一的。
在student.rb 文件中,我无法为在Student_section 模型中出现的standard and section 中的roll_no unique 设置自定义验证。
我在实施时遇到问题,有人可以帮忙吗?
【问题讨论】:
标签:
mysql
ruby-on-rails
validation
ruby-on-rails-4
model
【解决方案1】:
如果您使用的是 RAILS 4,您可以像这样定义模型的关系,如果为 true,则将从集合中省略重复项。
has_many :student_sections, -> { uniq }, through: :students
如果你使用的是 RAILS
has_many :student_sections, :through => :students, :uniq => true
【解决方案2】:
我同意您使用自定义验证器(这将允许您通过其错误消息以一致且详细的方式解释必须满足的条件)。您真正需要做的就是进行两个不同的查询并根据它们的结果返回:
def roll_no_must_be_unique
# Boolean indicating if roll_no is unique within the Student table
unique_in_student = Student.where(roll_no: roll_no).count == 0
# Boolean indicating if roll_no is unique within the Standard table
unique_in_standard = Standard.where(roll_no: roll_no).count == 0
# Adds the error if either query returned non-unique
errors.add(:roll_no, 'Error Message Here') unless unique_in_student && unique_in_standard
end
如果您愿意,您可以简单地在每个单独的查询之后添加一条错误消息,指出它在哪个表中失败。这真的是一个偏好问题。