Elusive Nil Object error on Comments

I have 2 models: Applicants and Comments. Applicants has_many Comments and Comments belongs_to Applicant.

If I add validation to my Applicants model (for example, "validates_presence_of :first_name") and edit the applicants page, I get a Nil Object error if I remove the first_name before saving. In this case I would expect to see the "there was 1 error that prevented..." error message. I do get this message during Applicant creation.

The strange part is that the error I do get points to my comments display. Everything works as expected. Why would it behave this way?

##### ERROR MESSAGE: Action Controller: Exception Caught

ebrad wrote:

#### CONTROLLER: applicants_controller.rb ##########################

  def edit     @applicant = Applicant.find(params[:id])     @comments = @applicant.applicant_comments.find(:all)   end

  def update     @applicant = Applicant.find(params[:id])     if @applicant.update_attributes(params[:applicant])       flash[:notice] = 'Applicant was successfully updated.'       redirect_to :action => 'list'     else       render :action => 'edit'     end   end

"render :action => 'edit'" renders the edit template but does not call the edit action which is seting the @comments variable.

Since you want to preserve the errors on @applicant, you'll have to copy down the @comments line.

That's exactly it! Thanks!

#### CONTROLLER: applicants_controller.rb ##########################

  def edit     @applicant = Applicant.find(params[:id])     @comments = @applicant.applicant_comments.find(:all)   end

  def update     @applicant = Applicant.find(params[:id])     if @applicant.update_attributes(params[:applicant])       flash[:notice] = 'Applicant was successfully updated.'       redirect_to :action => 'list'     else     @comments = @applicant.applicant_comments.find(:all)       render :action => 'edit'     end   end