ruby-on-rails - httparty NoMethodError: nil:NilClass 的未定义方法“[]”
问题描述
我使用 Ruby 2.5.0,httparty gem 我的模型
class FeedEntry
include Mongoid::Document
include Mongoid::Timestamps
field :guid, type: String
field :url, type: String
field :share_count, type: Integer, default: 2
before_update :share_info
def share_info
checked_url = self.url
json_stats = HTTParty.get("http://api.sharedcount.com/?url=#{checked_url}&apikey=#{Rails.application.credentials.socialshared_api_key}", timeout: 180, open_timeout: 1200)
self.share_count = json_stats['Facebook']['share_count']
end
end
当我尝试解析时出现此错误
NoMethodError: undefined method `[]' for nil:NilClass
/Users/ipatov/rails_projects/apps/tm/app/models/feed_entry.rb:71:in `share_info'
71 行self.share_count = json_stats['Facebook']['share_count']
解决方案
这是关于Rollbar 所说的最常见的错误之一
问题必须比json_stats['Facebook']
is nil
,因此访问 to['share_count']
会产生错误。我建议您使用dig来防止这种不希望出现的错误,并决定什么时候json_stats['Facebook']
是nil
.
self.share_count = json_stats.dig('Facebook', 'share_count')
推荐阅读
- ios - 在 Xamarin iOS 中拒绝位置权限时应用程序崩溃
- excel - 如果另一列等于值,则将单元格从一列复制到剪贴板的宏
- c++ - C++ 多级继承 - 调用基本构造函数错误
- java - 如何在 Maven 多模块项目中指定 log4j2 绝对路径?
- python-3.x - Celery 错误:即使 result.status 为 SUCCESS,result.get(timeout=5) 也会超时
- regex - XSD 模式限制。如何获得速记
- git-rebase - `Rebase and merge` 合并策略在 Bitbucket Server 上有什么作用?
- ajax - Ajax 获取带空格的响应正文数据名称
- python - 查询时如何正确设置json的嵌套dict路径
- java - Cactoos flatMap 类比