nil的未定义方法`to_date':NilClass

时间:2015-03-23 22:32:53

标签: ruby-on-rails ruby

我们如何解决此错误?由于用户没有养成这个习惯,因为date_started现在为空,所以它的原因是:

NoMethodError in Habits#new
Showing /Users/galli01anthony/Desktop/pecoce/app/views/habits/_form.html.erb where line #29 raised:
undefined method `to_date' for nil:NilClass
n_days = ((date_started.to_date)..Date.today).count { |date| committed_wdays.include? date.wday }

逻辑是levels可以计算自date_started以来已经过了多少天。

class Habit < ActiveRecord::Base
belongs_to :user
has_many :comments, as: :commentable
has_many :levels
serialize :committed, Array
validates :date_started, presence: true
before_save :set_level
acts_as_taggable
scope :private_submit, -> { where(private_submit: true) }
scope :public_submit, -> { where(private_submit: false) }

def save_with_levels
    self.levels.build
    self.levels.build
    self.levels.build
    self.levels.build
    self.levels.build
    self.save
end

def self.comitted_for_today
  today_name = Date::DAYNAMES[Date.today.wday].downcase
  ids = all.select { |h| h.committed.include? today_name }.map(&:id)
  where(id: ids)
end 

def levels
        committed_wdays = committed.map { |day| Date::DAYNAMES.index(day.titleize) }
        n_days = ((date_started.to_date)..Date.today).count { |date| committed_wdays.include? date.wday }
        actual_days = n_days - self.missed_days

  case n_days     
      when 0..9
        1
      when 10..24
        2
      when 25..44
        3
      when 45..69
        4
      when 70..99
        5
      else
        "Mastery"
    end
end

attr_accessor :missed_one, :missed_two, :missed_three

private
  def set_level
    self.level = levels
  end   
end

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

您可以为levels方法添加一个警卫:

def levels
  return 0 unless date_started

  # all the other code...
end