当用户开始习惯时,他会在表单中选择date_started
。
我们如何使用date_started
作为起点来确定并在索引中显示用户所在的level
?
在用户进入下一级别之前必须经过一定的天数(如下所示模型)。
目前,当用户查看索引时,他的所有习惯都会显示出来" Mastered"无论date_started
是什么。提前感谢您的专业知识=]
形式
<label> Started: </label>
<%= f.date_select :date_started, :order => [:month, :day, :year], class: 'date-select' %>
&#13;
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
case committed
when 0..9
1
when 10..24
2
when 25..44
3
when 45..69
4
when 70..99
5
else
"Mastered"
end
end
end
&#13;
控制器
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, :levels, :date_started, :trigger, :action, :target, :positive, :negative, :committed => [])
end
end
&#13;
答案 0 :(得分:1)
尝试这样的事情:
def levels
n_days = Integer(Date.today - date_started)
case n_days
when 0..9
1
when 10..24
2
...
end