module Elasticsearch::Model::Adapter::ActiveRecord::Records

Public Instance Methods

load() click to toggle source

Prevent clash with ‘ActiveSupport::Dependencies::Loadable`

# File lib/elasticsearch/model/adapters/active_record.rb, line 37
def load
  records.load
end
order(*args) click to toggle source

Intercept call to the ‘order` method, so we can ignore the order from Elasticsearch

# File lib/elasticsearch/model/adapters/active_record.rb, line 43
def order(*args)
  sql_records = records.__send__ :order, *args

  # Redefine the `to_a` method to the original one
  #
  sql_records.instance_exec do
    define_singleton_method(:to_a) do
      if defined?(::ActiveRecord) && ::ActiveRecord::VERSION::MAJOR >= 4
        self.load
      else
        self.__send__(:exec_queries)
      end
      @records
    end
  end

  sql_records
end
records() click to toggle source

Returns an ‘ActiveRecord::Relation` instance

# File lib/elasticsearch/model/adapters/active_record.rb, line 15
def records
  sql_records = klass.where(klass.primary_key => ids)

  # Re-order records based on the order from Elasticsearch hits
  # by redefining `to_a`, unless the user has called `order()`
  #
  sql_records.instance_exec(response.response['hits']['hits']) do |hits|
    define_singleton_method :to_a do
      if defined?(::ActiveRecord) && ::ActiveRecord::VERSION::MAJOR >= 4
        self.load
      else
        self.__send__(:exec_queries)
      end
      @records.sort_by { |record| hits.index { |hit| hit['_id'].to_s == record.id.to_s } }
    end
  end

  sql_records
end