Search code examples
ruby-on-railsnullappointment

You have a nil object when you didn't expect it (Appointments page)


Okay so I am creating an appointments site for professors and students to log on and create/edit appointments. I have the professors side done but I am struggling with the students. Right now I am trying to make it so students click a button next to their appointment to remove themselves from the appointment that they have with a professor. Now I could easily just delete the appointment id and the appointment would be gone but instead I want to remove the student_id from the appointment so other students could choose that appointment later. here is my code: THE CONTROLLER:

def destroy   
if session[:professor] != nil

    @appointment = Appointment.find(params[:id])
    @appointment.destroy
end
if session[:student] != nil
@appointment = Appointment.find_by_id_and_student_id(params[:id],params[:student_id])
@appointment.destroy(params[:student_id])  
end
end

VIEW:

<% @appointments.each do |appointment| %>
<tr>
<td><%= appointment.professor_id %></td>
<td><%= appointment.student_id %></td>
<td><%= appointment.timeslot %></td>
<td><%= link_to 'remove appointment', appointment, confirm: 'Are you sure?', method:  
:delete %></td>
</tr>
<% end %>

I have included the link here with my files if you want to take a look. CLICK HERE TO VIEW MY FILES. Also, everything takes place in the appointments controller. and this problem is in the show student view(where you press the delete button).

SOLUTION: Okay so I got it working due to the help I got from you guys. So here is what I did: @appointment = Appointment.find_by_id_and_student_id(params[:id], session[:student].user_id) @appointment.update_attribute(:student_id, nil)


Solution

  • Almost certainly the error here is that Appointment.find_by_id_and_student_id is returning nil. Refactor your code like this:

    @appointment = Appointment.find_by_id_and_student_id(params[:id],params[:student_id])
    if @appointment
      @appointment.destroy(params[:student_id])
    else
      flash[:error] = 'An appointment could not be found for that student.'
    end
    

    This will prevent you from receiving that error and should help you track down its root cause.