Rails迁移:仅用于模式更改还是用于数据更新? [英] Rails migration: only for schema change or also for updating data?

查看:98
本文介绍了Rails迁移:仅用于模式更改还是用于数据更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Rails的初级开发人员,在工作中我们遇到以下问题:

I'm a junior Rails developer and at work we faced the following problem:

只需要为一条记录更新列的值. 我们所做的就是创建这样的迁移:

Needed to update the value of a column only for one record. What we did is creating a migration like this:

class DisableAccessForUser < ActiveRecord::Migration
  def change
    User.where(name: "User").first.update_column(:access, false)
  end
end

迁移仅用于架构更改吗?

Are migrations only for schema changes?

您还建议其他什么解决方案?

What other solutions do you suggest?

PS:我只能用代码进行更改.无法访问控制台.

PS: I can only change it with code. No access to console.

推荐答案

简短的版本是,由于迁移仅用于架构更改,因此您不希望使用它们来更改数据库中的实际数据.

The short version is, since migrations are only for schema changes, you wouldn't want to use them to change actual data in the database.

主要问题是,如果其他开发人员使用rake db:schema:loadrake db:reset加载数据库结构,则您的数据操纵迁移可能会被忽略.两者都仅使用schema.rb文件加载结构的最新版本,并且不涉及迁移.

The main issue is that your data-manipulating migration(s) might be ignored by other developers if they load the DB structuring using either rake db:schema:load or rake db:reset. Both of which merely load the latest version of the structure using the schema.rb file and do not touch the migrations.

正如Nikita Singh在评论中还指出的那样,我也将说,更改行数据的最佳方法是实现一个简单的rake任务,该任务可以独立于迁移结构而根据需要运行.或者,对于第一次安装,seed.rb文件非常适合加载初始系统数据.

As Nikita Singh also noted in the comments, I too would say the best method of changing row data is to implement a simple rake task that can be run as needed, independent of the migration structure. Or, for a first time installation, the seed.rb file is perfect to load initial system data.

希望漫步会有所帮助.

更新

在一些官方"资源中找到了一些文档:

Found some documentation in some "official" sources:

  • Rails Guide for Migrations - Using Models in your Migrations. This section gives a description of a scenario in which data-manipulation in the migration files can cause problems for other developers.
  • Rails Guide for Migrations - Migrations and Seed Data. Same document as above, doesn't really explain why it is bad to put seed or data manipulation in the migration, merely says to put all that in the seed.rd file.
  • This SO answer. This person basically says the same thing I wrote above, except they provide a quote from the book Agile Web Development with Rails (3rd edition), partially written by David Heinemeier Hansson, creator of Rails. I won't copy the quote, as you can read it in that post, but I believe it gives you a better idea of why seed or data manipulation in migrations might be considered a bad practice.

这篇关于Rails迁移:仅用于模式更改还是用于数据更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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