【发布时间】:2015-05-01 04:32:42
【问题描述】:
我们怎么能这样称呼<%= habit.current_level.missed_days %>,我们只从current_level调用missed_days,而不是习惯上的所有missed_days(只是大致了解我们想要什么)。
例如,如果选中了两个框,则在习惯索引中调用 <%= habit.missed_days %> 将显示 2,如果选中了八个框,它将显示 8,但这里的目标是即使选中了 8 个框:
它仍然只会在索引中显示2 罢工,因为我们试图仅从当前级别计算missed_days。
class Habit < ActiveRecord::Base
belongs_to :user
has_many :comments, as: :commentable
has_many :levels
serialize :committed, Array
validates :date_started, presence: true
before_save :current_level
acts_as_taggable
scope :private_submit, -> { where(private_submit: true) }
scope :public_submit, -> { where(private_submit: false) }
attr_accessor :missed_one, :missed_two, :missed_three
def save_with_current_level
self.levels.build
self.levels.build
self.levels.build
self.levels.build
self.levels.build
self.save
end
def self.committed_for_today
today_name = Date::DAYNAMES[Date.today.wday].downcase
ids = all.select { |h| h.committed.include? today_name }.map(&:id)
where(id: ids)
end
def current_level
return 0 unless date_started
committed_wdays = committed.map { |day| Date::DAYNAMES.index(day.titleize) }
n_days = ((date_started.to_date)..Date.today).count { |date| committed_wdays.include? date.wday } - self.missed_days
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
我们在等级和习惯表中有t.integer "missed_days", default: 0。
missed_days 的大部分逻辑都可以追溯到它的控制器:
class DaysMissedController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
def create
habit = Habit.find(params[:habit_id])
habit.missed_days = habit.missed_days + 1
habit.save!
level = habit.levels.find(params[:level_id])
level.missed_days = level.missed_days + 1
level.save!
head :ok # this returns an empty response with a 200 success status code
end
def destroy
habit = Habit.find(params[:habit_id])
habit.missed_days = habit.missed_days - 1
habit.save!
level = habit.levels.find(params[:level_id])
level.missed_days = level.missed_days - 1
level.save!
head :ok # this returns an empty response with a 200 success status code
end
end
要点:https://gist.github.com/RallyWithGalli/c66dee6dfb9ab5d338c2
谢谢你的精彩!
【问题讨论】:
-
关卡模型在哪里?你能补充一下吗?只是想看看关联,MissedDay 也会有所帮助
标签: ruby-on-rails ruby model-view-controller methods integer