如何根据另一个表验证字段的唯一性

时间:2015-06-20 05:18:57

标签: mysql ruby-on-rails ruby validation ruby-on-rails-4

我想根据roll_no模型字段students验证student_section模型中的section字段,

student_section.rb

class StudentSection < ActiveRecord::Base
  validates :standard_id, :presence=> {:message=>" cannot be blank"}

  validates :section_id, :presence=> {:message=>" cannot be blank"}

  validates :student_id, :presence=> {:message=>" cannot be blank"}
end

我在student.rb中添加验证

class Student < ActiveRecord::Base
  validates :student_id, :presence=> true
  validates :student_name, :presence=> true

  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i

  validates :phone, :length=>{:in => 8..15}

  validates :admission_no, :uniqueness=> { scope: :org_id} 

  validates :roll_no, :uniqueness=> { scope: @student_section.section_id}
end

但它会抛出未知字段section_id

1 个答案:

答案 0 :(得分:0)

首先,您应该在StudentStudentSection之间建立关系。如果我理解正确,您可以创建one-to-many关系。 之后,您的验证应该可以正常工作。 但是,如果您要搜索更复杂的验证逻辑 - 您可以使用validates_with语句(validates_with at apidock.com