😽
データ移行方法
Rakeタスクを実行させる
- migrateファイル
class AddSerialNumberToUsers < ActiveRecord::Migration[6.1]
def change
add_column :users, :serial_number, :string, null: false, comment: 'シリアル番号'
end
end
- lib/tasks/set_serial_nuber_to_users.rake
namespace :user do
desc "userのserial_numberをセットする"
task set_serial_numbers: :environment do
ActiveRecord::Base.transaction do
# 連番を付与
User.order(:created_at).find_each do |user|
user.serial_number = User.generate_serial_number(user.created_at)
user.save(validate: false)
end
end
end
end
- model
- serial_numberに連番を付与している
class User < ApplicationRecord
before_create :set_serial_number
def self.generate_serial_number(date = Time.zone.today)
yymm = Util::TimeStamp.to_s(date, format: '%y%m')
number = ransack(serial_number_start: yymm).result.count + 1
yymm + format('%06d', number)
end
private
def set_serial_number
self.serial_number = self.class.generate_serial_number
end
end
- 実行コマンド
bundle exec rake user:set_serial_numbers
Discussion