【问题标题】:undefined local variable or method `n_days' when calling case variable in model method在模型方法中调用案例变量时未定义的局部变量或方法“n_days”
【发布时间】:2015-07-16 22:46:15
【问题描述】:

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

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

非常感谢您的专业知识!

【问题讨论】:

  • n_days 的范围是 current_level 方法,它只返回其中一个值以防万一。只要它返回n_days 就会超出范围。此外current_level 不接受参数,因此如果您希望n_days 可访问,您将获得ArgumentError,或者将其构建为方法并在需要时引用它,或者将其创建为实例变量并引用它。同样current_level 不返回Array 它返回一个字符串或整数,因此current_level[n_days] 最终将是一个字母nil,或者如果是整数,这将是位引用0 或1

标签: ruby-on-rails ruby methods model


【解决方案1】:

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

attr_accessor n_days,你应该很高兴。

除非它存储在您的数据库中的某个地方?很抱歉,不清楚。

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

【讨论】:

  • 作为注释current_level 不接受参数,因此您将获得ArgumentError: wrong number of arguments (1 for 0)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
相关资源
最近更新 更多