Sha256: e79f8e3c7839a0b2b6b4ab5a4c07aecbcafc3e22b01ea08c2b3dccf1dc191a7c

Contents?: true

Size: 1.36 KB

Versions: 4

Compression:

Stored size: 1.36 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|
        tasks = ForemanTasks::Task.joins(:locks).where(:locks => user_locks.where(:resource_id => owner_id))
        tasks.update_all(:user_id => owner_id)
        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

4 entries across 4 versions & 1 rubygems

Version Path
foreman-tasks-0.16.2 db/migrate/20180927120509_add_user_id.foreman_tasks.rb
foreman-tasks-0.16.1 db/migrate/20180927120509_add_user_id.foreman_tasks.rb
foreman-tasks-0.17.0 db/migrate/20180927120509_add_user_id.foreman_tasks.rb
foreman-tasks-0.16.0 db/migrate/20180927120509_add_user_id.foreman_tasks.rb