Rails迁移:仅用于模式更改还是用于数据更新? [英] Rails migration: only for schema change or also for updating data?
问题描述
我是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:load
或rake 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迁移指南-在迁移中使用模型一个>.本节介绍了一种情况,在该情况下,迁移文件中的数据处理可能会给其他开发人员带来问题.
- 迁移指南-迁移和种子数据.与上述相同的文档并没有真正说明为什么在迁移中放入种子或数据操作很不好,只是说将所有内容都放在
seed.rd
文件中. - 此答案.这个人基本上说了我上面写的相同的内容,除了他们提供了敏捷的Web开发与Rails(第三版)一书的引言,该书部分由 David Heinemeier Hansson 撰写, Rails的创建者.我不会复制引号,因为您可以在那篇文章中阅读它,但是我相信它可以使您更好地理解为什么迁移中的种子或数据操作可能被认为是不好的做法.
- 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屋!