Skip to content

Commit 0d236c8

Browse files
committed
[MODEL] Ensure that specified ActiveRecord order is not overwritten by Elasticsearch query order
1 parent 6c00612 commit 0d236c8

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

elasticsearch-model/lib/elasticsearch/model/adapters/active_record.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,11 @@ def records
3535
else
3636
self.__send__(:exec_queries)
3737
end
38-
@records.sort_by { |record| hits.index { |hit| hit['_id'].to_s == record.id.to_s } }
38+
if !self.order_values.present?
39+
@records.sort_by { |record| hits.index { |hit| hit['_id'].to_s == record.id.to_s } }
40+
else
41+
@records
42+
end
3943
end if self
4044
end
4145

elasticsearch-model/spec/elasticsearch/model/adapters/active_record_spec.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ class DummyClassForActiveRecord; end
9595

9696
before do
9797
records.instance_variable_set(:@records, records)
98+
allow(records).to receive(:order_values).and_return([])
9899
end
99100

100101
it 'reorders the records based on hits order' do
@@ -111,6 +112,7 @@ class DummyClassForActiveRecord; end
111112
before do
112113
records.instance_variable_set(:@records, records)
113114
expect(instance.records).to receive(:order).and_return(records)
115+
allow(records).to receive(:order_values).and_return([])
114116
end
115117

116118
it 'reorders the records based on hits order' do

elasticsearch-model/test/integration/active_record_basic_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,13 @@ def as_indexed_json(options = {})
231231
end
232232
end
233233

234+
should "allow ordering following any method chain in SQL" do
235+
if defined?(::ActiveRecord) && ::ActiveRecord::VERSION::MAJOR >= 4
236+
response = Article.search query: { match: { title: { query: 'test' } } }
237+
assert_equal 'Testing Coding', response.records.distinct.order(id: :desc).first.title
238+
end
239+
end
240+
234241
should "allow dot access to response" do
235242
response = Article.search query: { match: { title: { query: 'test' } } },
236243
aggregations: {

0 commit comments

Comments
 (0)