Rails 迁移:self.up 和 self.down 与更改 [英] Rails migrations: self.up and self.down versus change

查看:15
本文介绍了Rails 迁移:self.up 和 self.down 与更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来新的 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 方法是多余的(您可以在文档中看到 change 方法当前支持的方法).

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屋!

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