how to validate associated model id?

后端 未结 3 1364
忘了有多久
忘了有多久 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 11:02

    You can validate the presence of the course association. So, if does not exists, valid? will be false.

    Your class should be:

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

    The differences of validating foreign key and the association itself are explained at this post.

    If you don't need to validate presence of course, you can do this workaround:

    validates :course, presence: true, if: -> {course_id.present?}
    

提交回复
热议问题