当习惯标记为completed
时,我们如何将其从主页中删除,以便只显示未完成的习惯?
控制器
def home
@habits = current_user.habits.committed_for_today.order(:order)
end
habit.rb
class Habit < ActiveRecord::Base
belongs_to :user
has_many :levels, -> { order(:id) }
serialize :committed, Array
before_save :current_level
attr_accessor :missed_one, :missed_two, :missed_three
def completed=(boolean)
self.completed_at = boolean ? Time.current : nil
end
def completed
completed_at && completed_at >= Time.current.beginning_of_day
end
def self.committed_for_today
today_name = Date::ABBR_DAYNAMES[Date.today.wday].downcase
ids = all.select { |h| h.committed.include? today_name }.map(&:id)
where(id: ids)
end
def save_with_current_level
self.levels.build
self.levels.build
self.levels.build
self.levels.build
self.levels.build
self.save
end
def current_level_strike
levels[current_level - 1] # remember arrays indexes start at 0
end
def current_level
return 0 unless date_started
def committed_wdays
committed.map do |day|
Date::ABBR_DAYNAMES.index(day.titleize)
end
end
def n_days
((date_started.to_date)..Date.yesterday).count do |date|
committed_wdays.include? date.wday
end - self.real_missed_days
end
case n_days
when 0..9
1
when 10..24
2
when 25..44
3
when 45..69
4
when 70..99
5
else
6
end
end
def real_missed_days
value = 0
levels.each do |level|
value += level.missed_days + level.days_lost
end
value
end
def calculate_days_lost
def n_days
((date_started.to_date)..Date.yesterday).count do |date|
committed_wdays.include? date.wday
end - self.real_missed_days
end
case n_days
when 0..9
n_days
when 10..24
n_days-10
when 25..44
n_days-25
when 45..69
n_days-45
when 70..99
n_days-70
else
n_days-100
end
end
def days_left_in_current_level
def n_days
((date_started.to_date)..Date.yesterday).count do |date|
committed_wdays.include? date.wday
end - self.real_missed_days
end
case n_days
when 0..9
10-n_days
when 10..24
25-n_days
when 25..44
45-n_days
when 45..69
70-n_days
when 70..99
100-n_days
else
0 # No end
end
end
end
我尝试过范围,将completed
集成到方法committed_for_today
中,并在控制器中向@habits
添加其他方法。
答案 0 :(得分:2)
只需添加一个新范围,我们称之为incomplete
:
class Habit < ActiveRecord::Base
scope :incomplete, -> { where(completed_at: nil) }
end
然后在你的控制器中:
@habits = current_user.habits.committed_for_today.incomplete.order(:order)