如何在给定的季度创建每天的多个记录?

时间:2013-10-21 12:15:21

标签: ruby-on-rails ruby

我有 Shift 模型。

--- !ruby/object:Shift
attributes:
  id:
  starts_at:
  ends_at:

我想添加singelton方法来创建给定季度中每天的班次。

class Shift

  def self.open_quarter(number, year)
    starts_at = "08:00"
    ends_at = "08:00"

    ...
  end
end

如何以最佳方式实施?我希望每个班次从早上8点开始,到第二天早上8点结束。

2 个答案:

答案 0 :(得分:1)

def self.open_quarter(number, year)
  starts_at = "08:00 am"
  ends_at = "08:00 pm"

  quarter_start = Date.new(year, (number * 3)).beginning_of_quarter
  quarter_end = Date.new(year, (number * 3)).end_of_quarter

  (quarter_end - quarter_start).to_i.times do |n|
    start_shift = "#{(quarter_start + n).to_s} #{starts_at}".to_datetime
    end_shift = "#{(quarter_start + n).to_s} #{ends_at}".to_datetime

    Shift.create(starts_at: start_shift, ends_at: end_shift)
  end
end

答案 1 :(得分:1)

def self.open_quarter(number, year)   
 start_time = Time.new(year, number*3 - 2, 1, 8) 

  while start_time.month <= number*3 && start_time.year == year
      Shift.create{starts_at: start_time, ends_at: start_time += 24.hours}
  end
end

确保在使用Time.new时设置正确的时区。默认为当前时区(请参阅docs)。您也可以使用Time.utc