Sha256: 4301c8893351cb5efc91d9464e6ff4a5b278f0db9ebad551d94e5255e6b61c4f

Contents?: true

Size: 1.41 KB

Versions: 26

Compression:

Stored size: 1.41 KB

Contents

class AddUserId < ActiveRecord::Migration[5.0]
  def up
    add_reference :foreman_tasks_tasks, :user, :foreign_key => true

    return if User.unscoped.find_by(:login => User::ANONYMOUS_ADMIN).nil?
    User.as_anonymous_admin do
      user_locks.select(:resource_id).distinct.pluck(:resource_id).each do |owner_id|
        if User.exists?(:id => owner_id)
          tasks = ForemanTasks::Task.joins(:locks).where(:locks => user_locks.where(:resource_id => owner_id))
          tasks.update_all(:user_id => owner_id)
        end
        user_locks.where(:resource_id => owner_id).delete_all
      end
    end
  end

  def down
    User.as_anonymous_admin do
      ForemanTasks::Task.select(:user_id).distinct.pluck(:user_id).compact.each do |user_id|
        ForemanTasks::Task.where(:user_id => user_id).select(:id).find_in_batches do |group|
          group.each { |task| create_lock user_id, task }
        end
      end
    end

    remove_column :foreman_tasks_tasks, :user_id
  end

  private

  def create_lock(user_id, task)
    ForemanTasks::Lock.new(:name          => ForemanTasks::Lock::OWNER_LOCK_NAME,
                           :resource_type => User.name,
                           :resource_id   => user_id,
                           :task_id       => task.id,
                           :exclusive     => false).save!
  end

  def user_locks
    ForemanTasks::Lock.where(:name => ForemanTasks::Lock::OWNER_LOCK_NAME)
  end
end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
foreman-tasks-0.17.5 db/migrate/20180927120509_add_user_id.foreman_tasks.rb
foreman-tasks-0.17.4 db/migrate/20180927120509_add_user_id.foreman_tasks.rb
foreman-tasks-0.17.3 db/migrate/20180927120509_add_user_id.foreman_tasks.rb
foreman-tasks-0.17.2 db/migrate/20180927120509_add_user_id.foreman_tasks.rb
foreman-tasks-0.16.3 db/migrate/20180927120509_add_user_id.foreman_tasks.rb
foreman-tasks-0.17.1 db/migrate/20180927120509_add_user_id.foreman_tasks.rb