gpt4 book ai didi

ruby-on-rails - Mongoid Undefined method [] for nil :nilClass

转载 作者:可可西里 更新时间:2023-11-01 10:44:36 28 4
gpt4 key购买 nike

我有一个查询 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

最佳答案

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

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

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

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

关于ruby-on-rails - Mongoid Undefined method [] for nil :nilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12118517/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com