2012-08-25 33 views
2

我有一個應用程序查詢API,然後嘗試將該查詢存儲在Mongo文檔中。從文檔看來,這看起來非常簡單,但我似乎錯過了一個步驟,但我幾乎不知道發生了什麼問題。你們中的一個人能否指出我正確的方向?謝謝!Mongoid未定義方法[]爲零:nilClass

我有一行從數據庫中選擇一些記錄,然後運行循環查詢API。我碰上錯誤undefined method []」爲無: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 
+0

感謝您的建議。不瞭解這裏的禮儀。 – BBB

回答

1
從錯誤信息,我會說,這個問題已經無關

純Mongoid而不是cresult

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

如果這兩個中的任何一個沒有設置(nil),那麼語句失敗,你永遠不會到達Mongoid。

嘗試使用pry(pry-rails)並在上面的行插入binding.pry以檢查這兩個變量,看看它們中的任何一個是否爲零。

+0

我嘗試使用puts語句,並且'c ['id] .to_s'的值是1,result [「mood」]的值是負數,所以這兩個都不爲空 – BBB

+0

非常奇怪..很抱歉,那麼我就感到遺憾..也許你可以發佈你的模型代碼? 您可能還想從問題中刪除api鍵。 – Tigraine

相關問題