【问题标题】:You have a nil object when you didn't expect it (Appointments page)当你没想到时,你有一个 nil 对象(约会页面)
【发布时间】:2012-03-06 15:55:58
【问题描述】:

好的,我正在创建一个约会网站,供教授和学生登录并创建/编辑约会。我已经完成了教授方面的工作,但我正在与学生斗争。现在我正在努力让学生点击他们约会旁边的一个按钮,将自己从他们与教授的约会中删除。现在我可以轻松地删除约会 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. 此外,一切都发生在约会控制器中。这个问题出现在显示学生视图中(您按下删除按钮的位置)。

解决方案: 好的,由于我从你们那里得到了帮助,所以我得到了它的工作。所以这就是我所做的: @appointment = Appointment.find_by_id_and_student_id(params[:id], session[:student].user_id) @appointment.update_attribute(:student_id, nil)

【问题讨论】:

  • 错误发生在哪几行?
  • app/controllers/appointments_controller.rb:118:in `destroy'
  • 这无助于了解您提供的代码中的哪一行,因为它没有对行号的任何引用。在代码中添加注释,指出该行。
  • 抱歉,没有考虑。该行实际上是 116 并且是 @appointment.destroy(params[:student_id])

标签: ruby-on-rails null appointment


【解决方案1】:

几乎可以肯定这里的错误是 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

这将防止您收到该错误,并应帮助您找出其根本原因。

【讨论】:

  • 错误在一行:@appointment.destroy(params[:student_id])
  • 是的,但可能错误是@appointment 为零。因此,您需要在分配@appointment 的行上更正它。如果不是,那么您需要发布错误的回溯。
  • 另外,如果您必须将参数传递给destroy,则意味着appointment 不是单个模型对象,而是一个集合。
  • 抱歉忘记删除该行。好的,现在它只是刷新页面而不删除 student_id。但至少它现在正在读取 student_id。只是不从约会中删除它。
  • 是的,这不是从约会中删除 student_id 的适当语法。你应该使用@appointment.update_attribute(:student_id, nil)。即便如此,如果您的页面现在正在呈现,那么@appointment 很可能仍然为零。确保确实存在具有该 ID 和学生 ID 的约会。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
  • 2014-05-26
相关资源
最近更新 更多