Forum: Ruby on Rails Render error message for NULL object

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
6ce7537a93c6e45469b745b9f5ec7524?d=identicon&s=25 Justin Ko (jko170)
on 2007-01-02 09:35
I've got an student_id column in my Attendance table. The ID is found by
searching with the student's IDN in the before_create method:

class Attendance < ActiveRecord::Base
  belongs_to :student

  validates_numericality_of :student_id, :only_integer => true

  def before_create
    self.student = Student.find_by_idn(student_id)

This works just fine as long as the IDN that is entered is actually in
the Student table. If it is not, I get an error stating student_id is
NULL. How would I display "Student IDN not found" as an error message in
my view? I'm new to programming and tried this but it does not work:

  def before_create
    s = Student.find_by_idn(student_id)
    if s = nil
      errors.add(:student_id, "is not a valid IDN")
      self.student = s

Anyone have suggestions? Thanks for any help.
This topic is locked and can not be replied to.