Rails:更改生产数据库的最佳方法 [英] Rails: Best way to make changes to a production database

查看:107
本文介绍了Rails:更改生产数据库的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对正在使用的生产数据库进行更改.只需添加几列.我已经通过迁移对dev数据库进行了更改.在保留现有数据且不会过多干扰操作的同时更新生产数据库的最佳方法是什么?

I need to make changes to an in-use production database. Just adding a few columns. I've made the changes to the dev database with migrations. What is the best way to update the production database while preserving the existing data and not disrupting operation too much?

这是MYSQL,我将需要将数据也添加到已存在的记录的列中.一列可以有一个默认值(它是布尔值),但另一列是一个时间戳记,并且应该有一个任意的回溯值.行数不是很大.

It's MYSQL and I will be needing to add data to the columns as well for already existing records. One column can have a default value (it's boolean) but the other is a timestamp and should have an arbitrary backdated value. The row counts are not huge.

因此,如果我使用迁移,那么如何添加数据以及如何只执行这两个操作(或三个-我最初不是通过迁移构建生产数据库时,就在生产db上添加数据-最新的迁移)(我相信他们改用了架构)?

So if I use migrations how do I add data and how do I get it to just do the two (or three - I add data -latest migrations on the production db when it wasn't initially built via migrations (I believe they used the schema instead)?

推荐答案

听起来您处于生产db模式与您在dev中使用的模式不完全匹配的状态(尽管尚不完全清楚) .我会在沙子上画一条线,并使该产品数据库处于更好的状态.本质上,您要执行的操作是确保prod db具有"schema_info"表,该表列出了您不执行的所有迁移.曾经想在生产中运行.然后,您可以将迁移添加到您的心中内容,它们将与生产数据库一起工作.

It sounds like you're in a state where the production db schema doesn't exactly match what you're using in dev (although it's not totally clear). I would draw a line in the sand, and get that prod db in a better state. Essentially what you want to do is make sure that the prod db has a "schema_info" table that lists any migrations that you >don't< ever want to run in production. Then you can add migrations to your hearts content and they'll work against the production db.

完成后,您可以编写添加架构更改或添加数据的迁移,但是您需要特别注意的一件事是,如果使用迁移添加数据,则必须在迁移本身中定义模型,就像这样:

Once you've done that you can write migrations that add schema changes or add data, but one thing you need to be really careful about is that if you add data using a migration, you must define the model within the migration itself, like this:

class AddSomeColumnsToUserTable < ActiveRecord::Migration
  class User < ActiveRecord::Base; end
  def self.up
    add_column :users, :super_cool, :boolean, :default => :false
    u = User.find_by_login('cameron')
    u.super_cool = true
    u.save
  end

  def self.down
    remove_column :users, :super_cool
  end
end

这样做的原因是,将来在某些重构或其他过程中,您可能会完全删除该模型.如果您未在"User.find_by_login ..."行上定义用户类,则迁移将引发异常,这是一个很大的麻烦.

The reason for this is that in the future, you might remove the model altogether, during some refactoring or other. If you don't define the user class on line "User.find_by_login..." the migration will throw an exception which is a big pain.

这篇关于Rails:更改生产数据库的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆