在模型方法中调用案例变量时未定义的局部变量或方法“n_days”

undefined local variable or method `n_days' when calling case variable in model method

在我的习惯模型中我创建了一个新方法:

def current_level_days
  current_level[n_days]
end

如何在新方法中调用n_days的case变量,这样我才能实现我更大的目标Counting the Days from the current_level?

habit.rb

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 :current_level
    acts_as_taggable
    scope :private_submit, -> { where(private_submit: true) }
    scope :public_submit, -> { where(private_submit: false) }

attr_accessor :missed_one, :missed_two, :missed_three

    def save_with_current_level
        self.levels.build
        self.levels.build
        self.levels.build
        self.levels.build
        self.levels.build
        self.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 current_level_strike
      levels[current_level - 1] # remember arrays indexes start at 0
    end

    def current_level_days
      current_level(:n_days) # remember arrays indexes start at 0
    end

    def current_level
            return 0 unless date_started
            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 } - 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
end

要点https://gist.github.com/RallyWithGalli/c66dee6dfb9ab5d338c2

非常感谢您的专业知识!

您无法访问 current_level_days 中的 n_days,因为它尚未声明,因此未定义。在 class 的顶部添加:

attr_accessor n_days 你应该可以开始了。

除非它存储在您的数据库中的某个地方?不好意思不清楚。

但是,如果它存储在 table 中,您应该可以使用 self.n_days 访问它,因此 current_level(self.n_days) 应该在那个实例中工作