我在 heroku 上有一个应用程序,它可以从网站上抓取定价数据并定期保存。出于某种原因,每当我在本地运行 rake 任务时,它都会按预期运行,但是当我在 heroku 上运行该任务时,它会添加额外的输出并出于某种原因将对象保存两次。
当我在本地运行时输出
a,12.80 saved at 2012-10-26 03:36:17 UTC.
b,38.03 saved at 2012-10-26 03:36:24 UTC.
c,22.38 saved at 2012-10-26 03:36:31 UTC.
我在heroku上运行时的输出
a,12.80 saved at 2012-10-26 03:36:17 UTC.
b,38.03 saved at 2012-10-26 03:36:24 UTC.
c,22.38 saved at 2012-10-26 03:36:31 UTC.
#<Stock:0x000000047bb5e8>,12.80 saved at 2012-10-26 03:36:45 UTC.
#<Stock:0x000000047baaf8>,38.03 saved at 2012-10-26 03:36:48 UTC.
#<Stock:0x000000047b00a8>,22.38 saved at 2012-10-26 03:36:52 UTC.
代码
require 'open-uri'
require 'date'
namespace :data do
desc "import current blah stock price data to database"
task :importblah => :environment do
#pass in a stock and price and save it to the database
def save_stock(stock, price)
#store stock data in database
p = stock.prices.build
p.price = price
p.datetime = Time.now.utc.to_datetime
if p.save
puts "#{stock.symbol},#{price} saved at #{p.datetime.to_s}."
else
puts "#{stock.symbol} didn't save."
end
end
actives = Parent.where("test1 = ?", true)
actives.each do |m|
stocks = m.stocks.where('test2 = ?', false)
stocks.each do |stock|
if stock.title.start_with?('blah')
#grab stock price data from blah.com
url = "blah"+stock.symbol
doc = Nokogiri::HTML(open(url))
price = doc.at_css(".value").text[/\d+\.\d+/]
save_stock(stock, price)
end
end
end
end
end
对于不同的站点,我有一个几乎相同的 rake 任务,它没有两次保存定价数据。如果这会影响任何事情,我正在使用 Amazon RDS db。