Maintenance::BackfillTreeNodePrimaryTask

Source code
# frozen_string_literal: true

# Backfills tree_node_primary on TreeNodeToMboProfile join records.
#
# After the tree_node_primary column was added (default: false), existing joins
# all have tree_node_primary = false. This task promotes the earliest join
# (by created_at) per mbo_profile to tree_node_primary = true, matching the
# behaviour of the before_create callback introduced alongside the column.
#
# Safe to re-run: the collection excludes mbo_profiles that already have a
# primary join, and process re-checks immediately before writing.
class Maintenance::BackfillTreeNodePrimaryTask < MaintenanceTasks::Task
  collection_batch_size(1_000)

  def collection
    MboProfile
      .joins(:tree_node_to_mbo_profiles)
      .where.not(id: TreeNodeToMboProfile.where(tree_node_primary: true).select(:mbo_profile_id))
      .distinct
  end

  def process(mbo_profile)
    return if TreeNodeToMboProfile.exists?(mbo_profile_id: mbo_profile.id, tree_node_primary: true)

    earliest_join = TreeNodeToMboProfile.where(mbo_profile_id: mbo_profile.id)
                                        .order(created_at: :asc)
                                        .first
    earliest_join&.update(tree_node_primary: true)
  end
end

Previous Runs

Succeeded
#91

Processed 16,733 out of 16,733 items (100%).

Ran for 5 minutes, finished .

Metadata:
user_id
-1