NilClass による NoMethod エラーを回避しようとしています。私のコードは次のようになります。
@branded, @nonbranded, @unknown, @affiliate, @social, @referral, @paid, @direct, @email = [], [], [], [], [], [], [], [], []
count = 0
while count < 6
date = SDLW + count
#TODO There has to be a better way than this.
branded_check = Metric.first(start_date: date, end_date: date, source: 'branded')
nonbranded_check = Metric.first(start_date: date, end_date: date, source: 'nonbranded')
unknown_check = Metric.first(start_date: date, end_date: date, source: 'unknown')
affiliate_check = Metric.first(start_date: date, end_date: date, source: 'affiliate')
social_check = Metric.first(start_date: date, end_date: date, source: 'social')
referral_check = Metric.first(start_date: date, end_date: date, source: 'referral')
paid_check = Metric.first(start_date: date, end_date: date, source: 'paid')
direct_check = Metric.first(start_date: date, end_date: date, source: 'direct')
email_check = Metric.first(start_date: date, end_date: date, source: 'email')
branded_check = branded_check.nil? ? 0 : branded_check.visits
nonbranded_check = nonbranded_check.nil? ? 0 : nonbranded_check.visits
unknown_check = unknown_check.nil? ? 0 : unknown_check.visits
affiliate_check = affiliate_check.nil? ? 0 : affiliate_check.visits
social_check = social_check.nil? ? 0 : social_check.visits
referral_check = referral_check.nil? ? 0 : referral_check.visits
paid_check = paid_check.nil? ? 0 : paid_check.visits
direct_check = direct_check.nil? ? 0 : direct_check.visits
email_check = email_check.nil? ? 0 : email_check.visits
@branded << branded_check
@nonbranded << nonbranded_check
@unknown << unknown_check
@affiliate << affiliate_check
@social << social_check
@referral << referral_check
@paid << paid_check
@direct << direct_check
@email << email_check
count += 1
end
これを行うには、よりクリーンで簡潔な方法が必要だと確信しています。グーグルで調べたり読んだりしても、私はそれを理解することができませんでした。リファクタリングの方法に関するアイデアは大歓迎です。