Skip to content

[MODEL] Add the :includes option to ActiveRecord adapter #472

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,17 @@ module ActiveRecord
lambda { |klass| !!defined?(::ActiveRecord::Base) && klass.respond_to?(:ancestors) && klass.ancestors.include?(::ActiveRecord::Base) }

module Records
attr_writer :options

def options
@options ||= {}
end

# Returns an `ActiveRecord::Relation` instance
#
def records
sql_records = klass.where(klass.primary_key => ids)
sql_records = sql_records.includes(self.options[:includes]) if self.options[:includes]

# Re-order records based on the order from Elasticsearch hits
# by redefining `to_a`, unless the user has called `order()`
Expand Down
4 changes: 2 additions & 2 deletions elasticsearch-model/lib/elasticsearch/model/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ def results
#
# @return [Records]
#
def records
@records ||= Records.new(klass, self)
def records(options = {})
@records ||= Records.new(klass, self, options)
end

# Returns the "took" time
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ class Records

delegate :each, :empty?, :size, :slice, :[], :to_a, :to_ary, to: :records

attr_accessor :options

include Base

# @see Base#initialize
Expand All @@ -25,6 +27,7 @@ def initialize(klass, response, options={})
metaclass = class << self; self; end
metaclass.__send__ :include, adapter.records_mixin

self.options = options
self
end

Expand Down
10 changes: 10 additions & 0 deletions elasticsearch-model/test/unit/adapter_active_record_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,16 @@ def ids
instance.load
end

should "load the records with its submodels when using :includes" do
klass = mock('class', primary_key: :some_key, where: @records)
@records.expects(:includes).with([:submodel]).at_least_once

instance = DummyClassForActiveRecord.new
instance.expects(:klass).returns(klass).at_least_once
instance.options[:includes] = [:submodel]
instance.records
end

should "reorder the records based on hits order" do
@records.instance_variable_set(:@records, @records)

Expand Down