Rails 中未定义的方法 [] 是什么意思? [英] what do an undefined method [] mean in rails?

查看:59
本文介绍了Rails 中未定义的方法 [] 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:

undefined method `[]' for nil:NilClass

第 50 行中的相关代码段:

The related snippet in line 50:

 47: <%=h @contact.date_entered.to_date %></br>  
 48: Next event: 
 49: <% next_delayed_todo = @contact.next_delayed_todo %> 
 50: <% unless next_delayed_todo[:event].nil? %>
 52: <%= next_delayed_todo[:event].title %> </br>

推荐答案

看看您的视图中是如何连续 3 行只有代码的?这是一个标志,你应该把它拉到一个助手里,以保持你的观点干净.

See how you have 3 consecutive lines of nothing but code in your view? That's a sign you should pull it out into a helper, in order to keep your views clean.

新视图代码:

<%=h @contact.date_entered.to_date %></br>  
Next event: <%= next_delayed_todo(@contact) %> </br>

然后在你的助手中:

def next_delayed_todo(contact)
  contact.next_delayed_todo[:event].title rescue ""
end

请注意,您收到的错误是因为 next_delayed_todo 为零.helper 方法的第一行使用 rescue "" 设置一个替代值,如果它是 nil.您可以将其替换为 rescue "none." 或任何其他有意义的字符串.

Note that the error you were getting is because of next_delayed_todo being nil. The first line of the helper method uses rescue "" to set an alternate value if it is nil. You can replace it with rescue "none." or any other string that makes sense.

这篇关于Rails 中未定义的方法 [] 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆