DEV Community

David Paluy
David Paluy

Posted on

1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more