forked from External/greenlight
GRN2-xx: Switch the relation between users and roles to make queries cleaner and faster (#1299)
* First steps * Fixes in account creation flow * Fixed most testcases * more test fixes * Fixed more test cases * Passing tests and rubocop * Added rake task to remove rooms
This commit is contained in:
@ -19,7 +19,7 @@ class RolifyCreateRoles < ActiveRecord::Migration[5.0]
|
||||
add_index(:users_roles, [:user_id, :role_id])
|
||||
|
||||
User.all.each do |user|
|
||||
user.add_role(:user) if user.roles.blank?
|
||||
user.set_role(:user) if user.roles.blank?
|
||||
end
|
||||
end
|
||||
end
|
||||
|
29
db/migrate/20200413150518_add_role_id_to_users.rb
Normal file
29
db/migrate/20200413150518_add_role_id_to_users.rb
Normal file
@ -0,0 +1,29 @@
|
||||
# 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")
|
||||
.where("users_roles.user_id = '#{user.id}'").min_by(&:priority).id
|
||||
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
|
Reference in New Issue
Block a user