数据库操作实用技巧与解决方案
1. 安全地在迁移中使用模型
1.1 问题描述
迁移是数据库模式的版本控制。在任何时候,都应该能够从源代码控制仓库中检出代码的最新版本,并从头开始重建数据库模式。有时在迁移中执行模型级操作很有用,但如何在迁移中使用模型而不导致历史数据库模式和代码之间的版本不匹配问题呢?
1.2 解决方案
为确保迁移始终拥有所需模型的兼容版本,可以在迁移内部创建本地命名空间的模型类。示例代码如下:
class AddPositionToProducts < ActiveRecord::Migration
class Product < ActiveRecord::Base; end
class SoftwareProduct < Product; end
class CourseProduct < Product; end
def self.up
add_column :products, :position, :integer
Product.reset_column_information
# Set default list orders
SoftwareProduct.all.each_with_index {|p, i| p.position = i; p.save! }
CourseProduct.all.each_with_index {|p, i| p.position = i; p.save! }
end
def self.down
remove_
超级会员免费看
订阅专栏 解锁全文
1034

被折叠的 条评论
为什么被折叠?



