Run a single migration file

后端 未结 11 691
说谎
说谎 2020-11-30 16:01

Is there an easy way to run a single migration? I don\'t want to migrate to a certain version I just want to run a specific one.

相关标签:
11条回答
  • 2020-11-30 16:58

    As of rails 5 you can also use rails instead of rake

    Rails 3 - 4

    # < rails-5.0
    rake db:migrate:up VERSION=20160920130051
    

    Rails 5

    # >= rails-5.0
    rake db:migrate:up VERSION=20160920130051
    
    # or
    
    rails db:migrate:up VERSION=20160920130051
    
    0 讨论(0)
  • 2020-11-30 17:02

    If you're having trouble with paths you can use

    require Rails.root + 'db/migrate/20090408054532_add_foos.rb'
    
    0 讨论(0)
  • 2020-11-30 17:04

    If you've implemented a change method like this:

    class AddPartNumberToProducts < ActiveRecord::Migration
      def change
        add_column :products, :part_number, :string
      end
    end
    

    You can create an instance of the migration and run migrate(:up) or migrate(:down) on an instance, like this:

    $ rails console
    >> require "db/migrate/20090408054532_add_part_number_to_products.rb"
    >> AddPartNumberToProducts.new.migrate(:down)
    
    0 讨论(0)
  • 2020-11-30 17:06

    If you want to run it from console, this is what you are looking for:

    $ rails console
    irb(main)> require "#{Rails.root.to_s}/db/migrate/XXXXX_my_migration.rb"
    irb(main)> AddFoo.migrate(:up)
    

    I tried the other answers, but requiring without Rails.root didnt work for me.

    Also, .migrate(:up) part forces the migration to rerun regardless if it has already run or not. This is useful for when you already ran a migration, have kinda undone it by messing around with the db and want a quick solution to have it up again.

    0 讨论(0)
  • 2020-11-30 17:07

    Assuming fairly recent version of Rails you can always run:

    rake db:migrate:up VERSION=20090408054532
    

    Where version is the timestamp in the filename of the migration.

    Edit: At some point over the last 8 years (I'm not sure what version) Rails added checks that prevent this from running if it has already been run. This is indicated by an entry in the schema_migrations table. To re-run it, simply execute rake db:migrate:redo VERSION=20090408054532 instead.

    0 讨论(0)
提交回复
热议问题