Read more

Rails: Output helpers for migrations

Dominik Schöler
August 21, 2013Software engineer at makandra GmbH

When you're writing migrations that do more than changing tables (like, modify many records) you may want some output. In Rails > 3.1 you have two methods at hand: announce and say_with_time.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

In the migration:

class AddUserToken < ActiveRecord::Migration

  class User < ActiveRecod::Base; end

  def up
    add_column :users, :token, :string
    
    announce "now generating tokens"
    User.find_in_batches do |users|
      say_with_time "For users ##{users.first.id} to ##{users.last.id}" do
        users.each do |user|
          user.update_attribute :token, # ... generate token
        end
      end
    end
  end

end

Output:

==  AddUserToken: migrating =========================================
# ...
==  AddUserToken: now generating tokens =============================
-- For users #1 to #500
   -> 1.542s
   -> 1 rows
==  AddUserToken: migrated (1.0003s) ================================
Posted by Dominik Schöler to makandra dev (2013-08-21 18:18)