在我的习惯模型中,我创建了一个新方法:
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
非常感谢您的专业知识!
答案 0 :(得分:0)
您无法访问n_days
中的current_level_days
,因为它尚未被声明,因此未定义。在课程顶部添加:
attr_accessor n_days
你应该好好去。
除非它在某个地方存储在您的数据库中?对不起,我不清楚。
但是,如果它存储在表格中,您应该可以使用self.n_days
访问它,因此current_level(self.n_days)
应该在该实例中使用