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 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.