如何制作:等级特定天数?

时间:2015-02-10 20:43:58

标签: ruby-on-rails ruby

我正在创建一个习惯跟踪应用。每当用户开始新的习惯时,他必须完成5个等级才能认为自己是“主人”。

我想将等级(:level)分解为5,共计100天。

Levels   Days
1    =   10
2    =   15
3    =   20
4    =   25
5    =   30

如何创建上述关系?

我认为这是一个简单的问题,但我似乎无法弄明白。我是否将每个级别设为自己的字符串?t.string "levelone" t.string "leveltwo"等?

然后我会以某种方式将该数量等于模型中的X天数吗?

class Habit < ActiveRecord::Base
	belongs_to :user
	validates :action, presence: true
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")
   @mastered_habits = current_user.habits.mastered
   @challenge_habits = current_user.habits.challenge

  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, :days, :date_started, :trigger, :action, :target, :positive, :negative, :mastered)
    end
end

3 个答案:

答案 0 :(得分:0)

我不确定你的其他参数是做什么的,但我认为一般的想法会是这样的

t.string "habitname"
t.integer "levelone"
t.integer "leveltwo" etc.
t.references :user, index: true
t.timestamps null:false

然后在你的控制器中访问这些值

@habit = Habit.find(:id)
@habit.levelone = whatever days

答案 1 :(得分:0)

您可以只存储模型中的天数,并添加一个返回该数字级别的方法。无需在模型中存储:level,只需:days

class Habit < ActiveRecord::Base
    belongs_to :user
    validates :action, presence: true

    def get_level
        case days
        when 0..10
           1
        when 11..15
           2
        when 16..20
           3
        when 21..25
           4
        else
           5
        end
    end

end

答案 2 :(得分:0)

如果我理解正确,您需要等级virtual attribute

def levels
  case days
  when 0..9
    1
  when 10..24
    2
  when 25..44
    3
  when 45..69
    4
  when 70..99
    5
  else
    6
end

等级6为主等级。