2015-05-28 109 views
0

獲取價值希望你能幫我解決無法找到答案的問題。 我有這個程序,並試圖檢索&更新數據庫中的記錄值。在Rails應用程序無法從Mongo DB Rails Rake

我耙命令如下:

task :nokogiri => :environment do 

require 'nokogiri' 
require 'open-uri' 

doc = Nokogiri::XML(open(url)) 

    data = doc.at_css(".lister-list") 
    movies = data.css('.titleColumn') 
    current_time = Time.now.strftime("%d/%m/%Y %H:%M") 
    movies.each do |movie| 

     headline = movie.text.strip 
     found = Movie.where("title" => headline).first 

     if found.nil? 
     title = Movie.new 
     title._id = BSON::ObjectId.new 
     title.title = headline 
     title.current_time = current_time.to_s 
     title.save 
     puts "Record created" 
     else 
     # arr = found.to_a.to_json 
     # puts arr.title 
     puts found.title 
     puts "Record exist" 
     end 
    end 
end 

的問題是,我可以輸出「ARR」對象安慰,但我不能夠檢查標題字段。我不斷收到:

rake aborted! 
NoMethodError: undefined method `title' for #<String:0x007f68589d93e8> 

我在這裏做錯了什麼?我如何用current_time更新記錄?

p.s.我是新手,所以你的幫助會幫助我很多,你是最後一個能幫助我的人。

謝謝!

編輯:答案很簡單,有功能,我們必須限制結果,並把它放在。首先。然後,我們可以得到對象值照常found.title

回答

1

else分支你這樣說:

arr = found.to_a.to_json 

to_json返回String。然後你說:

puts arr.title 

但沒有String#title方法,所以你得到一個NoMethodError。也許你的意思是說:

puts found.title 

此外,你真的是說found.to_a.to_json而非found.to_jsonto_a調用只需在單個元素數組中包裝found即可。

+0

謝謝你的迴應。我已經嘗試了很多方法,這只是代碼的最後一個版本。但是,您的解決方案工作。在開始時,我沒有使用「.first」方法找到對象,這就是爲什麼我在「puts found.title」上出現錯誤。問題最終解決。 – saulenzo7