1

如何编写 Ruby on Rails 迁移以生成日历表,所有日期都在 2010 年 1 月到 2099 年 12 月之间?

4

2 回答 2

4

当我再次发现这个问题时,供我自己参考。

架构:

create_table :calendar_days, primary_key: :day, id: :date do |t|
  t.integer :year, null: false
  t.integer :month, null: false
  t.integer :day_of_month, null: false
  t.integer :day_of_week, null: false
  t.integer :quarter, null: false
  t.boolean :business_day, null: false
  t.boolean :week_day, null: false
end

class CalendarDay < ActiveRecord::Base
  self.primary_key = :day
end

数据:

# Non-exhaustive, needs to be customized for your needs.
def business_day?(d)
  matches = ->(month, day) { [month, day] == [d.month, d.day] }
  falls_on = ->(month, wday, r) {
    [month, wday] == [d.month, d.wday] && r.cover?(d.day)
  }

  return false if [0,6].include?(d.wday) # Weekends
  return false if matches[1, 1]   # New Years
  return false if matches[7, 4]   # Independence Day
  return false if matches[12, 25] # Christmas
  return false if matches[11, 11] # Veterans Day
  return false if falls_on[1,  1, 15..21] # MLK Day
  return false if falls_on[5,  1, 25..31] # Memorial Day
  return false if falls_on[9,  1, 1..7]   # Labor Day
  return false if falls_on[11, 4, 22..28] # Thanksgiving
  true
end

task populate_calendar_days: :environment do
  (Date.new(2013,1,1)...Date.new(2014,1,1)).each do |d|
    CalendarDay.create!(
      day:          d,
      year:         d.year,
      month:        d.month,
      day_of_month: d.day,
      day_of_week:  d.wday,
      quarter:      (d.month / 4) + 1,
      week_day:     ![0,6].include?(d.wday),
      business_day: business_day?(d)
    )
  end
end
于 2013-09-21T16:35:23.843 回答
1

我不明白你在做什么,但如果你想用 2010 年 1 月到 2099 年 12 月的日期填充表格并进行迁移,

你可以用一些东西

class CreateCalendar < ActiveRecord::Migration
  def change
    create_table :calendars do |t|
      t.date :date
      t.timestamps
    end
  end
  (Date.new(2010,1,1)..Date.new(2099,12,31)).each do |date|
    Calender.create(:date=> date )
  end
end
于 2012-07-07T21:39:43.410 回答