如何编写Ruby on Rails迁移以生成日历表,其中所有日期都在2010年1月至2099年12月之间?Rails迁移以生成日历表
0
A
回答
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
1
当我再次发现这个问题时,请自己参考。
模式:
create_table :calendar_days, id: false do |t|
t.date :day, null: false
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
execute "ALTER TABLE calendar_days ADD PRIMARY KEY (day)"
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|
day = CalendarDay.new(
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)
)
day.day = d
day.save!
end
+0
感谢分享!真的很有帮助 – 2015-05-18 13:19:40
相关问题
- 1. Rails迁移未生成迁移文件
- 2. Rails - 从模型生成迁移脚本
- 3. 无法在rails上生成迁移2.3.4
- 4. 在Rails之外生成迁移
- 5. Rails的生成迁移文件支架
- 6. 从模式生成Rails迁移
- 7. Rails迁移表
- 8. 生成日历
- 9. 如何生成迁移以更改Rails中的数据库列
- 10. 从Rails模式更新生成迁移,而不是以其他方式生成
- 11. 生成日历日期列表
- 12. 如何使用Rails :: Generators.invoke(“active_record:migration”)生成创建表迁移文件?
- 13. Asp.net日历 - 生成日期
- 14. Rails DB迁移错误,Rails重新运行以前的迁移?
- 15. 自动生成新迁移
- 16. Rails的迁移产生不产生列
- 17. 您可以使用Doctrine生成现有表的迁移吗?
- 18. Rails ActiveRecord迁移成功迁移后不创建一些列
- 19. rails HABTM迁移
- 20. Rails迁移
- 21. Rails将日期迁移到字符串?
- 22. Rails 5 - 在rake任务中生成并运行迁移
- 23. Rails 3生成迁移 - 没有向上或向下的方法
- 24. Ruby on Rails自定义迁移生成器
- 25. 插件中的生成器和迁移(rails 3)
- 26. 有没有办法不生成在rails中的迁移文件
- 27. 命令'rails生成迁移CreateUsers'的哪个方法调用?
- 28. 生成的Rails模型 - 迁移将如何运行?
- 29. 我无法在rails中生成模型或迁移
- 30. “迁移:创建”和“迁移:生成”之间有什么区别?
(1)你尝试过什么? (2)你确定你需要一个日历表吗?有些数据库(如PostgreSQL)有更好的方法。 – 2012-07-07 21:00:17
我正在使用PostgreSQL。什么是更好的方法来实现这一目标? – Myxtic 2012-07-07 21:24:28
['generate_series'](http://www.postgresql.org/docs/current/static/functions-srf.html) – 2012-07-07 21:29:33