未定义的局部变量或方法`n_days'在模型方法

时间:2015-05-06 16:46:42

标签: ruby-on-rails ruby methods model

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

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

非常感谢您的专业知识!

1 个答案:

答案 0 :(得分:0)

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

attr_accessor n_days你应该好好去。

除非它在某个地方存储在您的数据库中?对不起,我不清楚。

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