我正在创建一个习惯跟踪应用。
当用户养成习惯时,他会将:date_started
放入其中:committed
以及:committed
做习惯。
然后,在:levels
天的X量后,习惯移动到下面的date_started
,直到最终达到“掌握”(等级中的天数在模型中被分解下文)。
我已经发现了:levels
。
现在我们怎样才能使用承诺的日子而不是任何一天来计算习惯的等级?
:levels
是一种动态getter方法,目前对数据库没有任何影响。
我被告知在保存记录之前我需要一个适当的回调来设置<%= f.label "Committed to:" %>
<%= f.collection_check_boxes :committed, Date::DAYNAMES, :downcase, :to_s %>
属性,但我不知道如何。
你会接受这个挑战吗?
形式
class Habit < ActiveRecord::Base
belongs_to :user
validates :action, presence: true
serialize :committed, Array
scope :missed, -> { where(missed: 1) }
scope :nonmissed, -> { where(missed: 0) }
def levels
committed_wdays = committed.map { |day| Date::DAYNAMES.index(day) }
n_days = (date_started..Date.today).count { |date| committed_wdays.include? date.wday }
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
class HabitsController < ApplicationController
before_action :set_habit, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@habits = Habit.all.order("date_started DESC")
@missed_habits = current_user.habits.missed
@nonmissed_habits = current_user.habits.nonmissed
end
def show
end
def new
@habit = current_user.habits.build
end
def edit
end
def create
@habit = current_user.habits.build(habit_params)
if @habit.save
redirect_to @habit, notice: 'Habit was successfully created.'
else
render action: 'new'
end
end
def update
if @habit.update(habit_params)
redirect_to @habit, notice: 'Habit was successfully updated.'
else
render action: 'edit'
end
end
def destroy
@habit.destroy
redirect_to habits_url
end
private
def set_habit
@habit = Habit.find(params[:id])
end
def correct_user
@habit = current_user.habits.find_by(id: params[:id])
redirect_to habits_path, notice: "Not authorized to edit this habit" if @habit.nil?
end
def habit_params
params.require(:habit).permit(:missed, :left, :level, :date_started, :trigger, :action, :target, :positive, :negative, :committed => [])
end
end
控制器
{{1}}
Github :https://github.com/RallyWithGalli/ruletoday
提前感谢您的专业知识=]