Ruby on rails 获得;未定义的方法`包括?'&引用;对于request.user\u代理

Ruby on rails 获得;未定义的方法`包括?'&引用;对于request.user\u代理,ruby-on-rails,include,user-agent,Ruby On Rails,Include,User Agent,我有一行代码: if request.user_agent.include?("iPhone") then 但我偶尔会遇到这样的错误: "undefined method `include?' for nil:NilClass" 检查错误日志时,对于收到错误的用户,没有“HTTP\u USER\u AGENT” 因此,我如何修复该行,以便在没有HTTP\u USER\u代理时不会抛出错误?检查它是否为零,或者自己拯救异常 对于Rails 2.3.xx,您也可以使用Object#try r

我有一行代码:

if request.user_agent.include?("iPhone") then 
但我偶尔会遇到这样的错误:

"undefined method `include?' for nil:NilClass"
检查错误日志时,对于收到错误的用户,没有“
HTTP\u USER\u AGENT


因此,我如何修复该行,以便在没有
HTTP\u USER\u代理时不会抛出错误?

检查它是否为零,或者自己拯救异常

对于Rails 2.3.xx,您也可以使用Object#try


request.user\u agent.try(:include?,'iphone')

查看更多信息。

NSD是正确的

您也可以使用
try
作为捷径:

request.user_agent.try(:include?, "iPhone")
try
在其接收器为nil时不会出错,因此您可以将它们链接在一起,如下所示:

foo.try(:bar).try(:baz)