如何验证相关模型的id? [英] how to validate associated model id?

查看:118
本文介绍了如何验证相关模型的id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个学生和课程模式。学生属于当然,当然有许多学生。

I have a student and a course model. Student belongs to course, and course has many students.

class Student < ActiveRecord::Base
  attr_accessible :course_id, :name, :password, :status, :studentID, :year
  belongs_to :course

  validates :name, :password, :status, :studentID, :year, :presence =>true
  validates_associated :course
end

class Course < ActiveRecord::Base
  attr_accessible :courseCode, :courseName, :courseYr
  validates :courseCode,:courseName,:courseYr, :presence => true
  validates :courseCode,:courseYr, :uniqueness=>{:message=>"Cannot repeat the code"}

  has_many :students 
end

在用于创建学生记录的形式,我让用户输入过程ID。

In the form used to create student record, I let the user enter the course ID.

<div class="field">
  <%= f.label :course_id %><br />
  <%= f.text_field :course_id %>
</div>

但我不知道如何通过用户验证 COURSE_ID 输入。当我输入一个不存在的课程ID的学生模型验证不会产生错误,甚至是。我如何得到它显示错误?

But I don't know how to validate the course_id input by the user. The student model validation will not generate an error, even when I type a course ID that does not exist. How do I get it to show the error?

推荐答案

您应该考虑创建一个自定义的验证方法:

You should look into creating a custom validation method:

class Student < ActiveRecord::Base
  validates :course_id, presence: true, numericality: { only_integer: true }
  ...
  validate :validate_course_id

private

  def validate_course_id
    errors.add(:course_id, "is invalid") unless Course.exists?(self.course_id)
  end
end

首先,你的模型将确保该 COURSE_ID 是一个有效的整数,然后你自定义的验证将确保该过程中存在于数据库中。

First, your model will make sure that the course_id is a valid integer, and then your custom validation will make sure that the course exists in the database.

这篇关于如何验证相关模型的id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆