Rails迁移:self.up和self.down与变更 [英] Rails migrations: self.up and self.down versus change
问题描述
看起来新的rails版本相对于self.up和self.down方法具有更改"功能.
Looks like the new rails version has "change" versus self.up and self.down methods.
因此,当必须回滚迁移时会发生什么,它如何知道要执行的操作.我需要基于在线教程实现以下方法:
So what happens when one has to roll back a migration how does it know what actions to perform. I have the following method that I need to implement based on an online tutorial:
class AddImageToUsers < ActiveRecord::Migration
def self.up
add_column :users, :image_file_name, :string
add_column :users, :image_content_type, :string
add_column :users, :image_file_size, :integer
add_column :users, :image_updated_at, :datetime
end
def self.down
remove_column :users, :image_file_name, :string
remove_column :users, :image_content_type, :string
remove_column :users, :image_file_size, :integer
remove_column :users, :image_updated_at, :datetime
end
end
如何使用新的更改方法来做同样的事情?
How can I do the same using the new change method?
推荐答案
对于许多操作 rails可以猜测什么是逆操作(没有问题).例如,在您的情况下,回滚时调用add_column
的反向操作是什么?当然是remove_column
. create_table
的逆是什么? drop_table
.因此,在这些情况下,rails知道如何回滚和定义down
方法是多余的(您可以在文档中看到
For many operations rails can guess what is the inverse operation (without problems). For example, in your case what is the reverse operation of add_column
to call when you rollback? Of course it's remove_column
. What is the inverse of create_table
? It's drop_table
. So in these cases rails know how to rollback and define a down
method is superfluous (you can see in the documentation the methods currently supported from the change method).
但是要注意,因为对于某种操作,您仍然需要定义down
方法,例如,如果您更改小数列的精度,那么如何猜测回滚时的原始精度?这是不可能的,因此您需要定义down
方法.
But pay attention because for some kind of operation you still need to define the down
method, for example if you change the precision of a decimal column how to guess the original precision on rollback? It's not possible, so you need to define the down
method.
如上所述,建议您阅读《 Rails迁移指南》 .
As said, I suggest you to read the Rails Migrations Guide.
这篇关于Rails迁移:self.up和self.down与变更的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!