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,
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?}