【发布时间】:2018-05-07 15:57:20
【问题描述】:
我使用 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']
【问题讨论】:
-
显然,
json_stats['Facebook']为零。而且你不能在零时打电话给['share_count']。因此错误。 -
@jvillian 如何避免这种情况?
-
也许您应该将
json_stats的内容添加到您的问题中。