Mongoid Undefined method [] for nil:nilClass

时间:2012-08-25 01:49:08

标签: ruby-on-rails mongodb mongoid

我有一个查询API的应用程序,然后尝试将该查询存储在Mongo文档中。从文档中看起来非常简单,但我似乎错过了一步,但我不知道出了什么问题。你们其中一个人能指出我正确的方向吗?谢谢!

我有一行从数据库中选择一些记录,然后运行查询API的循环。当程序到达行时,我遇到错误undefined method []'为nil:NilClass`

EntityMetadata.where(id: c['id'].to_s).add_to_set(:mood, result["mood"])

控制台还会输出:MOPED: 127.0.0.1:27017 COMMAND database=admin command={:ismaster=>1},我不知道它是如何到达那里的。

如果您有兴趣,这是完整的代码

puts "Getting sentiment for all entities from Viralheat..."
api_key = '___________------_____-----'
puts "a"
base_uri 'viralheat.com/api/sentiment'

content_sql = 'SELECT content,id FROM entities'   
puts content_sql

content = ActiveRecord::Base.connection.select_all(content_sql , "Entity Content")
query = {:api_key => api_key}
asdf = {}
content.each do |c| 
   puts c["content"]
   puts "Getting Sentiment for " + c["content"].to_s 
   query[:text] = c["content"]
   result = self.get('/review.json', :query => query)
   puts "asdf"
   EntityMetadata.where(id: c['id'].to_s).add_to_set(:mood, result["mood"])
   puts "ss"
   EntityMetadata.where(id: c['id'].to_s).add_to_set(:prob, result["prob"])
   #update_mood_sql = "UPDATE entities SET mood = '#{result["mood"]}' WHERE id ='" + c["id"].to_s + "'"
   #update_prob_sql = "UPDATE entities SET probability = '#{result["prob"]}' WHERE id ='" + c["id"].to_s + "'"
   #ActiveRecord::Base.connection.update_sql(update_mood_sql, "Updating mood")
   #ActiveRecord::Base.connection.update_sql(update_prob_sql, "Updating prob")  
end

以下是型号代码:

class EntityMetadata
  include Mongoid::Document
  field :_id, type: Integer
  field :fingerprint, type: String
  index({ fingerprint: 1 }, { sparse: true })

  # TODO: change this to use the entity_id as the :_id field, to save space
  # field :entity_id, type: Integer
  # index({ entity_id: 1 }, { unique: true })

  def entity
    @entity ||= Entity.find_by_id(self._id)
  end
end

1 个答案:

答案 0 :(得分:1)

纯粹从错误消息中我会说问题与Mongoid无关,而是与cresult无关:

EntityMetadata.where(id: c['id'].to_s).add_to_set(:mood, result["mood"])

如果未设置这两个中的任何一个(nil),则该语句将失败,您实际上永远不会到达Mongoid。

尝试使用pry(pry-rails)并在上面的行中插入binding.pry来检查这两个变量,看看它们是否都是零。