如何添加:承诺天数:水平?

时间:2015-02-13 02:26:13

标签: ruby-on-rails ruby date text integer

在计算习惯的等级时,我们怎样才能使用: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

1 个答案:

答案 0 :(得分:1)

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

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