我有一个名为 TradeDailyAverage 的模型的数据库表。它有一个date
(DateTime) & averageprice
(decimal) 列
当我运行它时,我无法更新 averageprice 属性:
newaverage = TradeDailyAverage.find_or_initialize_by_date(date)
newaverage.update_attributes :averageprice => dailyaverage
此外,当我运行它时,日期会显示出来,但平均价格不会显示在 rails 控制台中。它只显示为空白:
newaverage = TradeDailyAverage.find_or_initialize_by_date(date)
puts newaverage.averageprice
puts newaverage.date
在保存之前,我需要对平均价格做些什么特别的事情吗?
以下是整个 Rake 任务供您参考:
averages = Trade.where('date >= ?', 7.days.ago).average(:price, :group => "DATE_TRUNC('day', date - INTERVAL '1 hour')")
# Loops through each daily average produced above
averages.each do |date, avg|
# Converts the BigDecimal to Floating Point(?)
averagefloat = avg.to_f
# Rounds the Daily Average to only two decimal points
dailyaverage = number_with_precision(averagefloat, :precision => 2)
newaverage = TradeDailyAverage.find_or_initialize_by_date(date)
newaverage.update_attributes :averageprice => dailyaverage