how to validate associated model id?

后端 未结 3 1370
忘了有多久
忘了有多久 2021-02-03 10:07

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,         


        
3条回答
  •  走了就别回头了
    2021-02-03 10:54

    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
    

    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.

提交回复
热议问题