【问题标题】:migration steps change, up and down迁移步骤变化,向上和向下
【发布时间】:2016-06-22 20:52:44
【问题描述】:

我的问题很简单。我创建了这个迁移文件,我的移动专栏没有改变,但 def change 已创建。是因为rails忽略了def updef down吗?如果是,为什么?

def change
  add_column :posts, :address, :string
end


def up
 execute 'ALTER TABLE posts ALTER COLUMN mobile TYPE integer USING (mobile::integer)'
end

def down
  execute 'ALTER TABLE posts ALTER COLUMN mobile TYPE text USING (mobile::text)'

end

【问题讨论】:

    标签: ruby-on-rails database postgresql ruby-on-rails-4 migration


    【解决方案1】:

    Rails 在设计上不会同时运行 change 和 up 方法,因此会忽略 change 方法之后的所有内容。当您需要在 Up 和 Down 方法中运行某些特定逻辑时,您有两种选择。您可以将 change 方法中的内容放入 up 和 down 方法中,也可以将 Up 和 Down 内容放入 change 方法中。如果您想以“Rails4”方式执行此操作,您应该使用changereversible 方法来获得您需要的内容:

    class SomeMigration < ActiveRecord::Migration
    
     def change
        add_column :posts, :address, :string
    
        reversible do |change|
          change.up do
           execute 'ALTER TABLE posts ALTER COLUMN mobile TYPE integer USING (mobile::integer)'
          end
    
          change.down do
            execute 'ALTER TABLE posts ALTER COLUMN mobile TYPE text USING (mobile::text)'
          end
        end
      end
    

    【讨论】:

      猜你喜欢
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 2011-06-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      相关资源
      最近更新 更多