20200413150518_add_role_id_to_users.rb 829 Bytes
Newer Older
Ahmad Farhat's avatar
Ahmad Farhat committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# frozen_string_literal: true

class MigrationProduct < ActiveRecord::Base
  self.table_name = :users
end

class SubMigrationProduct < ActiveRecord::Base
  self.table_name = :roles
end

class AddRoleIdToUsers < ActiveRecord::Migration[5.2]
  def change
    reversible do |dir|
      dir.up do
        add_reference :users, :role, index: true

        MigrationProduct.where(role_id: nil).each do |user|
          highest_role = SubMigrationProduct.joins("INNER JOIN users_roles ON users_roles.role_id = roles.id")
19
                                            .where("users_roles.user_id = '#{user.id}'")&.min_by(&:priority)&.id
Ahmad Farhat's avatar
Ahmad Farhat committed
20
21
22
23
24
25
26
27
28
29
          user.update_attributes(role_id: highest_role) unless highest_role.nil?
        end
      end

      dir.down do
        remove_reference :users, :role, index: true
      end
    end
  end
end