DEV Community

David Paluy
David Paluy

Posted on

Rails Migration custom Direction Action

Image description

There are several options to specify direction dependent actions in Rails applications

Example 1 - reversible

class AddSlugToUserss < ActiveRecord::Migration
  def change
    add_column :users, :slug, :string, limit: 64
    add_index :users, :slug, unique: true

    reversible do |dir|
      dir.up do
        User.find_each(&:save)
      end
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Reference: https://apidock.com/rails/ActiveRecord/Migration/reversible

Example 2 - up_only

class AddSlugToUserss < ActiveRecord::Migration
  def change
    add_column :users, :slug, :string, limit: 64
    add_index :users, :slug, unique: true

    up_only do |dir|
      User.find_each(&:save)
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Reference: https://apidock.com/rails/ActiveRecord/Migration/up_only

Top comments (0)