Sha256: 0417c5add68e76f0621e823df48d546f433e1e02b9d11e4ef74ee9ff0c60398e

Contents?: true

Size: 1.03 KB

Versions: 2

Compression:

Stored size: 1.03 KB

Contents

module Superstore
  module Associations
    class HasMany < Association
      def reader
        unless loaded?
          self.target = load_collection
        end

        target
      end

      def writer(records)
        relation = load_collection

        # TODO: Use relation.load_records with Rails 5
        relation.instance_variable_set :@records, records
        relation.instance_variable_set :@loaded, true

        self.target = relation
      end

      def set_inverse_instance(record)
        return unless reflection.inverse_name

        inverse = record.association(reflection.inverse_name)
        inverse.target = owner
      end

      private

        def inverse_of
          return unless reflection.inverse_name

          @inverse_of ||= association_class.reflect_on_association reflection.inverse_name
        end

        def load_collection
          AssociationScope.new(association_class, self).where("document ->> '#{reflection.foreign_key}' = '#{owner.try(reflection.primary_key)}'")
        end

    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
superstore-3.0.0 lib/superstore/associations/has_many.rb
superstore-2.5.0 lib/superstore/associations/has_many.rb