问题描述
我是一名初级 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 加载数据库结构,您的数据操作迁移可能会被忽略:重置
.两者都只是使用 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 迁移指南 - 在迁移中使用模型.本部分描述了迁移文件中的数据操作可能会给其他开发人员带来问题的场景.
- Rails 迁移指南 - 迁移和种子数据.与上面相同的文档,并没有真正解释为什么在迁移中放置种子或数据操作是不好的,只是说将所有这些都放在
seed.rd
文件中. - 这个答案.这个人基本上说的和我上面写的一样,只是他们引用了Agile Web Development with Rails(第3版)一书,部分由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 迁移:仅用于模式更改还是用于更新数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2