Class: Role

Inherits:
ApplicationRecord show all
Includes:
CaberSubject
Defined in:
app/models/role.rb

Constant Summary collapse

ROLES =
[
  :administrator,   # Can do everything
  :moderator,       # Can edit any models
  :contributor,     # Can upload models and edit their own
  :member,          # Can view models; read only access
  :printer          # Can send models to configured printers
]

Constants inherited from ApplicationRecord

ApplicationRecord::SAFE_NAME_LENGTH

Class Method Summary collapse

Methods inherited from ApplicationRecord

find_param

Class Method Details

.merge_duplicates! ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'app/models/role.rb', line 30

def self.merge_duplicates!
  ActiveRecord::Base.transaction do
    ROLES
      .map { |n| Role.where(name: n) } # rubocop:disable Pundit/UsePolicyScope
      .select { |r| r.count > 1 }
      .each do |roles|
        original, *duplicates = roles.order(created_at: :desc)
        Caber::Relation.where(subject_type: "Role", subject_id: duplicates.map(&:id)).update_all(subject_id: original.id) # rubocop:disable Rails/SkipsModelValidations, Pundit/UsePolicyScope
        duplicates.each do |dupe|
          # Rename duplicate role to something different
          dupe.update_attribute :name, "#{dupe.name}##{dupe.id}"  # rubocop:disable Rails/SkipsModelValidations
          # Find all users with the new named role
          # and give them the original role, before removing the dupe
          User.with_role(dupe.name).each do |user|
            user.add_role(original.name)
          end
          dupe.destroy
        end
      end
  end
end