Rails 方法忽略默认参数 - 为什么?
我不知道为什么会发生这种情况。我有以下功能:
def as_json(options = {})
json = {
:id => id,
# ... more unimportant code
}
unless options[:simple]
# ... more unimportant code
end
json
end
它在大多数情况下都有效,但在我称之为的一个特定部分中:
window.JSONdata = <%= @day.to_json.html_safe %>
我收到以下错误:
ActionView::Template::Error (当您没有预料到时,您有一个 nil 对象! 您可能期望一个 Array 的实例。 评估 nil.[]) 时发生错误:
指向“unless options[:simple]”行。据我所知,选项哈希为零 - 因此该方法忽略默认参数分配。为什么?我可以通过将方法更改为来解决此问题:
def as_json(options)
options ||= {}
json = {
:id => id,
# ... more unimportant code
}
unless options[:simple]
# ... more unimportant code
end
json
end
这对任何人都有意义吗!?非常感谢您的帮助。
I am at a loss as to why this is happening. I have the following function:
def as_json(options = {})
json = {
:id => id,
# ... more unimportant code
}
unless options[:simple]
# ... more unimportant code
end
json
end
It works most of the time, but in one particular partial where I call this:
window.JSONdata = <%= @day.to_json.html_safe %>
I get the following error:
ActionView::Template::Error (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]):
Pointing to the line "unless options[:simple]". As far as I can tell, the options hash is nil - thus the method is ignoring the default param assignment. WHY? I can fix this by changing the method to:
def as_json(options)
options ||= {}
json = {
:id => id,
# ... more unimportant code
}
unless options[:simple]
# ... more unimportant code
end
json
end
Does this make any sense to anyone!? Most appreciative for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为您使用的是
to_json
,它的默认options
为nil
。to_json
最终将调用as_json
并将nil
作为options
传递。这是 Rails 源代码中发生的地方。首先,
to_json
是使用默认options
的nil
定义的。最终它会到达这里。
如您所见,使用
value.as_json(options_for(value))
调用as_json
,并且options_for(value)
将返回默认值 < code>to_json,即nil
。This is because you're using
to_json
, which has a defaultoptions
ofnil
.to_json
will eventually callas_json
and pass thenil
asoptions
.Here's where it happens on the Rails source code. First,
to_json
is defined with the defaultoptions
ofnil
.Eventually it will arrive here.
As you see,
as_json
is called withvalue.as_json(options_for(value))
andoptions_for(value)
will return the default value ofto_json
, which isnil
.