gpt4 book ai didi

ruby-on-rails - 异常处理 : "undefined method ` ___ _' for nil:NilClass"

转载 作者:太空宇宙 更新时间:2023-11-03 16:54:36 25 4
gpt4 key购买 nike

我的 Web 应用程序失败的最常见原因之一是因为用户有时缺少 View 期望它具有的特定属性。例如,我的应用程序中的大多数用户在我们的系统中都有教育(学校、学位等)条目,但有些用户没有。假设我的 View 看起来像这样:

<% @educations.each do |education| %>
<%= education.school %>
<%= education.degree %>
<% end %>

我想避免“Pokemon”异常处理,并且觉得必须有更好的方法来处理“undefined method ‘degree’ for nil:NilClass”错误,以防用户没有教育条目在我们的数据库中。这看起来像是一个丑陋/乏味的修复:

<% @educations.each do |education| %>
<% if education.school %>
<%= education.school %>
<% end %>
<% if education.degree %>
<%= education.degree %>
<% end %>
<% end %>

欢迎任何意见。谢谢!

最佳答案

只要你知道你正在处理的第一个对象不会是 nil,最简单的方法就是这样做:

- @educations.each do |education|
= education.try :school
= education.try :degree

#try方法很方便。您还可以对任何您认为可能为零的内容调用 .to_s,即:

- @educations.each do |education|
= education.school.to_s
= education.degree.to_s

这会将 nils 转换为空字符串。这在 IMO View 中不是很有用,但如果您的输入预期是一个字符串并且可能为空,那么它会派上用场很多次。即像这样的方法:

def put_in_parenthesis(string)
"(" + string.to_s + ")"
end

关于ruby-on-rails - 异常处理 : "undefined method ` ___ _' for nil:NilClass",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13260609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com