好的,我正在为教授和学生创建一个约会网站,以登录并创建/编辑约会。我有教授方面,但我正在与学生们斗争。现在我正努力让学生点击他们预约旁边的按钮,将他们自己从教授的约会中删除。现在我可以轻松地删除约会ID,但约会将会消失,但我想从约会中删除student_id,以便其他学生可以稍后选择该约会。这是我的代码: 控制器:
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
查看:
<% @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 %>
如果您想查看,我已将此链接包含在我的文件中。 CLICK HERE TO VIEW MY FILES. 此外,一切都发生在约会控制器中。这个问题出现在show student视图中(按下删除按钮)。
解: 好的,所以我得到了它的工作,因为我得到了你们的帮助。所以这就是我所做的: @appointment = Appointment.find_by_id_and_student_id(params [:id],session [:student] .user_id) @ appointment.update_attribute(:student_id,nil)
答案 0 :(得分:0)
这里的错误几乎肯定是Appointment.find_by_id_and_student_id返回nil。像这样重构你的代码:
@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
这可以防止您收到该错误,并且可以帮助您找出其根本原因。