我有一个事件表和会话表。活动has_many会议,这是该协会。现在我想将会话表中的time_zone列仅移动到事件表中。那么如何在迁移的帮助下做到这一点。如何将会话表中的time_zone现有记录移至事件表中?在rails移植中更新数据列
0
A
回答
-1
您可以简单地使用以下迁移。
class Test < ActiveRecord::Migration
def change
add_column :events, :time_zone, :string
Event.all.each do |e|
e.update_attributes(time_zone: e.sessions.last.time_zone)
end
remove_column :sessions, :time_zone
end
end
1
首先,您需要确保与同一事件关联的会话具有相同的时区。你可以这样做:
Session.group(:event_id).count(:time_zone)
这将返回一个哈希映射的event_id
到与它相关联的时区的数量。这个数字应该总是一个。其次,我建议您先添加events.time_zone
,并在新代码投入生产一段时间后开始使用它并删除sessions.time_zone
,并证明可以正常工作。
三,增加events.time_zone
应该是这样的迁移(我加为清楚起见,一些评论):
class AddTimeZoneToEvents < ActiveRecord::Migration
class Event < ActiveRecord::Base; end
class Session < ActiveRecord::Base; end
def up
# Add a NULLable time_zone column to events. Even if the column should be
# non-NULLable, we first allow NULLs and will set the appropriate values
# in the next step.
add_column :events, :time_zone, :string
# Ensure the new column is visible.
Event.reset_column_information
# Iterate over events in batches. Use #update_columns to set the newly
# added time_zone without modifying updated_at. If you want to update
# updated_at you have at least two options:
#
# 1. Set it to the time at which the migration is run. In this case, just
# replace #update_columns with #update!
# 2. Set it to the maximum of `events.updated_at` and
# `sessions.updated_at`.
#
# Also, if your database is huge you may consider a different query to
# perform the update (it also depends on your database).
Event.find_each do |event|
session = Session.where(event_id: event.id).last
event.update_columns(time_zone: session.time_zone)
end
# If events don't always need to have time zone information then
# you can remove the line below.
change_column_null :events, :time_zone, false
end
def down
remove_column :events, :time_zone
end
end
注意,我在迁移重新定义模型。这是至关重要的,因为:
- 原始模型可能有回调和验证(当然,您可以跳过它们,但它是一个额外的预防措施,贡献零值)。
- 如果您在路上6个月内移除模型,迁移将停止工作。
确定您的更改按预期工作后,您可以删除sessions.time_zone
。如果出现问题,您可以简单地回滚上述迁移并轻松恢复工作版本。
相关问题
- 1. 数据库在rails移植中没有完全更新
- 2. 在Rails移植中将一列更新为另一列值
- 3. Rails 3数据库移植
- 4. 将数组列更新为Rails移植中另一个文本列的值
- 5. 在rails中更新数据库列
- 6. Rails新迁移不更新旧数据
- 7. mysql中的数据移植
- 8. 在rails移植中添加对非整数列的引用
- 9. 移植在Rails中创建不同的数据库结构
- 10. Rails移植列类型多态
- 11. 通过移植更新实体框架数据库
- 12. 在rails移植中设置postgres datetime列为零
- 13. Rails无移植创建表
- 14. 新贵Systemd移植
- 15. 如何处理数据库更改并移植我的数据?
- 16. 打印移植源变更散列
- 17. Ruby on Rails中的迁移是否更新到数据库?
- 18. 不使用rails中的迁移更新数据库模式
- 19. Rails移植中的PostgreSQL点类型
- 20. 在Rails迁移中迁移数据
- 21. 移植到iOS 5中核心数据的新API:了解NSConfinementConcurrencyType
- 22. 如何生成迁移以更改Rails中的数据库列
- 23. 如何在rails 3.x迁移中更改新列的位置
- 24. Rails更新海量数据
- 25. Rails更新旧数据库
- 26. 向Rails移植中的现有表添加列
- 27. 重命名rails移植中的列的每个条目(或行)
- 28. 移植物抗移植
- 29. 在应用更新中更新核心数据数据库而无需迁移
- 30. Rails 3:更新数据库数据
您不应该在迁移中使用模型。他们可以触发回调,验证等,并且可以随时间变化(即如果您在6个月内移除模型,迁移将停止工作)。 –