0
我正在根據帳戶餘額創建圖表。這裏是我的我的一些代碼Rails:按時間劃分錯誤圖表
module AccountsHelper
def products_chart_data
orders_by_day = Account.total_grouped_by_day(3.days.ago)
(3.days.ago.to_date..Date.today).map do |date|
{
created_at: date,
balance: orders_by_day[date].first.try(:total_balance) || 0
}
end
end
end
class Account < ActiveRecord::Base
belongs_to :user
has_many :books
def self.total_grouped_by_day(start)
balances = where(created_at: start.beginning_of_day..Time.zone.now)
balances = balances.group("date(created_at)")
balances = balances.select("created_at, balance as total_balance")
balances.group_by {|o| o.created_at.to_date }
end
end
我的問題是:
1)映射3.days.ago的時候,卻成功運行的代碼時,我改變我收到一個錯誤未定義的方法`第一」它到2.days.ago。我知道這是因爲我3天前沒有數據,因爲這個帳戶是新的。我的問題是,我該如何解決這個錯誤,因爲我可能還有很多其他沒有數據的新帳戶,我該如何顯示1個月或2個月的結果?
在此先感謝!
謝謝!不知道我可以使用第一/最後一次嘗試。由於沒有記錄的日子的餘額設置爲0,如果我希望餘額等於前一天的餘額,我該怎麼寫呢? – pyfl88
請問另一個問題。 SO規則是每個問題的一個問題。 – mudasobwa