【问题标题】:Mongoid Undefined method [] for nil:nilClass用于 nil:nilClass 的 Mongoid 未定义方法 []
【发布时间】:2012-08-25 01:49:08
【问题描述】:

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

我有一行从数据库中选择一些记录,然后运行一个循环查询 API。当程序到达该行时,我遇到了错误undefined method[]' for 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

【问题讨论】:

  • 感谢您的建议。不懂这里的礼仪。

标签: ruby-on-rails mongodb mongoid


【解决方案1】:

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

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

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

尝试使用 pry (pry-rails) 并在上面的行中插入 binding.pry 以检查这两个变量是否都为 nil。

【讨论】:

  • 我尝试使用 puts 语句,c['id].to_s 的值为 1,result["mood"] 的值为负,所以这两个都不是 null
  • 很奇怪..对不起,我很茫然..也许你可以发布你的模型代码?不过,您可能还想从问题中删除 api 密钥..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
  • 2013-02-17
  • 2014-03-16
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多