如何将 :committed 天数添加到 :levels?

How to Add :committed Days to :levels?

我们如何只用 :committed 天来计算习惯的级别?

每个 :levels 都有不同的天数,在习惯进入下一个级别之前必须经过这些天数(如下面的 模型 所示)。

目前t.text :committedt.integer :levels没有意义。让我们改变它!预先感谢您的专业知识 =]

形式

<%= f.label "Committed to:" %>&nbsp;
<%= 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
   n_days = Integer(Date.today - date_started)

  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, :levels, :date_started, :trigger, :action, :target, :positive, :negative, :committed => [])
    end
end

假设 committed 是一个包含日期名称数组的字段(例如 ['Monday', 'Friday'],以下应该有效:

committed_wdays = committed..map { |day| Date::DAYNAMES.index(day) }
n_days = (date_started..Date.today).count { |date| committed_wdays.include? date.wday }