2010-09-30 43 views
0

我得到以下错误:在轨道中,未定义的方法[]意味着什么?

undefined method `[]' for nil:NilClass 

的相关片段中第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> 

回答

1

看看你如何在你的视图中连续3行只是代码?这是一个标志,你应该把它出来帮助,以保持你的观点清洁。

新视图代码:

<%=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是零。辅助方法的第一行使用rescue ""来设置一个替代值,如果它是零。您可以用rescue "none."或任何其他有意义的字符串替换它。

+0

虽然没有回答问题,但这是我需要做的有益改变......谢谢+1 – Angela 2010-10-01 00:46:58

+0

它对您的问题提供了*解决方案*,但我添加了一条使其明确的注释。 – 2010-10-01 13:20:54

+0

啊,是的 - 救援也是我看到的解决方案的关键组成部分.... – Angela 2010-10-02 16:24:08

2

这意味着,你叫[] nil对象上。在这种情况下,next_delayed_todo为零。

你想要更类似于: 除非next_delayed_todo.nil? || next_delayed_todo [:事件] .nil?

+0

嗨,我有下面几行代码了:<%,除非next_delayed_todo.nil? || next_delayed_todo [:事件] .nil? %>嗯...所以不完全确定该怎么办... – Angela 2010-10-01 00:24:36

+0

啊,有趣的...它在我的本地,但不是在heroku我想...让我做一些调整。 – Angela 2010-10-01 00:26:59

2

这意味着NilClass不执行[]方法。这又意味着,在你的代码中,next_delayed_todo是零。

.nil?你现在检查next_delayed_todo [:event]返回的值是否为零。你还应该添加一个零检查next_delayed_todo

0

NoMethodError:是从异常派生的类,是一个例外。在强动态类型语言中,如果您尝试在不存在该方法的类型上使用方法,则会抛出一个错误的类型异常。

的method_missing是一个功能 -http://ruby-doc.org/core/classes/Kernel.html#M005925

Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.

我觉得(不相信我这一点)默认的method_missing函数执行类似NoMethodError的消息“#{inspectVariableValue}:#{ClassName}”的消息“undefined method#{method_name}'。

0

我在代码中看到一个错误,除非应该启动一个块,否则,就像它写入的行一样。 所以这应该工作:

<%=h @contact.date_entered.to_date %></br> 
Next event: 
<% next_delayed_todo = @contact.next_delayed_todo %> 
<% unless next_delayed_todo[:event].nil? do %> 
    <%= next_delayed_todo[:event].title %> </br> 
<% end %> 
相关问题