如何修复level.rb使用:承诺的日子?

最初我有:committed日子工作得非常漂亮,但是在更改模型时,为了适应用户的检查能力,如果他错过了:committed一天我现在收到与以下代码相关的错误消息:committed

undefined method to_date for nil:NilClass Line#30 n_days = ((date_started.to_date)..Date.today).count { |date| committed_wdays.include? date.wday } n_days = ((date_started.to_date)..Date.today).count { |date| committed_wdays.include? date.wday }

此代码来自习惯模型:

 class Habit < ActiveRecord::Base belongs_to :user has_many :levels has_many :days, through: :levels #for being able to access Habit.find(*).days accepts_nested_attributes_for :levels, :days before_save :set_level acts_as_taggable serialize :committed, Array def evaluate(user) levels.each { |level| level.evaluate } user.missed_levels << levels.where(passed: false).ids user.missed_days << days.where(missed: true).ids user.save end def self.committed_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 } 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 private def set_level self.level = levels end end 

这背后的逻辑是用户创造了他想要挑战的习惯。 要达到“掌握”的习惯,他必须完成5个等级。 每个级别都有一定数量的:committed天数必须在推进之前完成,如上面用n_days

用户在_form中承诺他想要养成什么日子(周日至周六)。 例如,他可以选择太阳,婚礼,坐着。 然后应用程序应该只根据non计算n_days :missed :committed days(这些天中有10天通过它进入第二级)。

 class Level < ActiveRecord::Base belongs_to :habit belongs_to :user has_many :days accepts_nested_attributes_for :days def evaluate if days.where(missed: true ).count == days_needed update_attributes(passed: false) else update_attributes(passed: true) end end end 

 class Day < ActiveRecord::Base belongs_to :level belongs_to :habit end 

 class HabitsController  [], :levels_attributes => [ :passed, :days_attributes => [ :missed,:level_id]]) end end 

   
 

[:month, :day, :year], class: 'date-select' %>

Level


  

HABITS

Level Left Strike Trigger Action Target Reward Days

非常感谢你的帮助!

这里的一些代码来自这里的答案: 如何整合:错过的日子:习惯的日子.rb? 这搞砸了这个答案的工作原理: 如何制作:级别变更基于:承诺的日子?

似乎date_started是您的Habit模型的属性,可能是数据库列,并且date_started中有NULL。 打开你的Rails控制台,看看是否是这种情况:

 Habit.where(date_started: nil).count 

如果您希望date_started永远不应为null,请添加validation以确保是这种情况。 只要您测试将空值保存到该列的代码,validation错误就会指向您的错误。

另一方面,如果要在date_started允许空值,则重写levels方法以允许该值。