Reputation: 1710
I am creating a chart based on account balance. And here is my some of my codes
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
My problems are:
1) I received an error undefined method `first' when mapping 3.days.ago, but successfully run the code when I change it to 2.days.ago. I understand that it is because I do not have data on 3 days ago as this account is new. My question is, how can I rescue this error, because I could have many other new accounts that do not have data yet, and what could I do to display result for 1 month, or 2 month?
Thanks in advance!
Upvotes: 0
Views: 25
Reputation: 121000
# ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓
balance: orders_by_day[date].try(:first).try(:total_balance) || 0
try
is the method, introduced by rails and defined on Object
class, therefore it is defined on NilClass
as well.
The implementation is quite straightforward: it checks whether receiver is empty and returns either the result of the call to it, or nil
otherwise.
Upvotes: 1