【问题标题】:Rails migrations: self.up and self.down versus changeRails 迁移:self.up 和 self.down 与更改
【发布时间】:2012-05-09 01:22:46
【问题描述】:

看起来新的 rails 版本与 self.up 和 self.down 方法相比有“变化”。

那么当一个人必须回滚迁移时会发生什么,它如何知道要执行什么操作。我有以下方法需要根据在线教程实现:

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

如何使用新的更改方法来做同样的事情?

【问题讨论】:

标签: ruby-on-rails migration rails-activerecord rails-migrations


【解决方案1】:

对于许多操作rails 可以猜出什么是逆操作(没有问题)。例如,在您的情况下,回滚时调用add_column 的反向操作是什么?当然是remove_columncreate_table 的倒数是什么?这是drop_table。所以在这些情况下,rails 知道如何回滚并定义 down 方法是多余的(您可以在文档中看到 methods currently supported from the change method)。

但是要注意,因为对于某种操作你仍然需要定义down方法,例如如果你改变一个十进制列的精度,如何猜测回滚时的原始精度?这是不可能的,所以你需要定义down方法。

如前所述,我建议你阅读Rails Migrations Guide

【讨论】:

    【解决方案2】:

    更好地使用 Up、Down、Change:

    On Rails 3 (Reversible):应该在 up 上添加新列并仅在 up 时填充表中的所有记录,并且只在 down 时删除此列

    def up
      add_column :users, :location, :string
      User.update_all(location: 'Minsk')
    end
    
    def down
      remove_column :users, :location
    end
    

    但是:

    您必须避免使用可以节省一些时间的更改方法。例如,如果您不需要在添加后立即更新列值,您可以将此代码缩减为如下所示:

    def change
      add_column :users, :location, :string
    end
    

    向上时,它会将列添加到表中,并在向下时将其删除。少得多的代码,这是一种利润。

    On Rails 4:在一个地方编写我们需要的东西的另一种有用的方法:

    def change
      add_column :users, :location, :string
      reversible do |direction|
        direction.up { User.update_all(location: 'Minsk') }
      end
    end
    

    【讨论】:

    • 很好的解释兄弟
    • 还原?也是告诉你在变化中前进方向的好方法
    • 这些都不起作用。我只是不断收到ActiveRecord::IrreversibleMigration
    • 存在 Rails 无法回滚迁移的情况。请查看他们的help
    【解决方案3】:
    class AddImageToUsers < ActiveRecord::Migration
      def change
        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
    end
    

    【讨论】:

    • 谢谢。但是如果你回滚会发生什么。它会知道该怎么做吗?
    • 我睡过头了。 Aldo 'xoen' Giambelluca 解释了一切。
    猜你喜欢
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多