Sha256: 7cd92487ffb8a7e19a65a2c30eb271feb37c0b6cb0761bfe862f4282fce5376f

Contents?: true

Size: 1.65 KB

Versions: 5

Compression:

Stored size: 1.65 KB

Contents

# frozen_string_literal: true

module PaperTrail
  module Reifiers
    # Reify a single `belongs_to` association of `model`.
    # @api private
    module BelongsTo
      class << self
        # @api private
        def reify(assoc, model, options, transaction_id)
          id = model.send(assoc.foreign_key)
          version = load_version(assoc, id, transaction_id, options[:version_at])
          record = load_record(assoc, id, options, version)
          model.send("#{assoc.name}=".to_sym, record)
        end

        private

        # Given a `belongs_to` association and a `version`, return a record that
        # can be assigned in order to reify that association.
        # @api private
        def load_record(assoc, id, options, version)
          if version.nil?
            assoc.klass.where(assoc.klass.primary_key => id).first
          else
            version.reify(
              options.merge(
                has_many: false,
                has_one: false,
                belongs_to: false,
                has_and_belongs_to_many: false
              )
            )
          end
        end

        # Given a `belongs_to` association and an `id`, return a version record
        # from the point in time identified by `transaction_id` or `version_at`.
        # @api private
        def load_version(assoc, id, transaction_id, version_at)
          assoc.klass.paper_trail.version_class.
            where("item_type = ?", assoc.klass.base_class.name).
            where("item_id = ?", id).
            where("created_at >= ? OR transaction_id = ?", version_at, transaction_id).
            order("id").limit(1).first
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
paper_trail-9.1.1 lib/paper_trail/reifiers/belongs_to.rb
paper_trail-9.1.0 lib/paper_trail/reifiers/belongs_to.rb
paper_trail-9.0.2 lib/paper_trail/reifiers/belongs_to.rb
paper_trail-9.0.1 lib/paper_trail/reifiers/belongs_to.rb
paper_trail-9.0.0 lib/paper_trail/reifiers/belongs_to.rb