【问题标题】:How to validate uniqueness of field based on another table如何根据另一个表验证字段的唯一性
【发布时间】:2015-09-06 04:04:03
【问题描述】:

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

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

【问题讨论】:

  • validates_uniqueness_of :roll_no, scope: :section_id 工作了吗?
  • StudentStudentSection是什么关系?
  • 它抛出 Mysql2::Error: Unknown column 'students.section_id' @Pavan
  • 确保你的学生表中有 section_id 列
  • 请发布您的模型。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2011-09-20
    相关资源
    最近更新 更多