Skip to content

Commit 44bf526

Browse files
committed
Add ids method as in AR
1 parent f952b9f commit 44bf526

3 files changed

Lines changed: 40 additions & 0 deletions

File tree

lib/active_graph/node/query/query_proxy_methods.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,11 @@ def first_and_last(func, target)
270270
end.first
271271
end
272272

273+
# @return [Array] An array of primary key values
274+
def ids
275+
pluck(association_id_key)
276+
end
277+
273278
# @return [String] The primary key of a the current QueryProxy's model or target class
274279
def association_id_key
275280
self.association.nil? ? model.primary_key : self.association.target_class.primary_key

lib/active_graph/node/query_methods.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,13 @@ def find_each(options = {})
4949
end
5050
end
5151

52+
# Returns an array of all the IDs (primary key values) of the model's nodes.
53+
# ActiveRecord-compatible shortcut for `pluck(primary_key)`.
54+
# @return [Array] An array of primary key values
55+
def ids
56+
self.all.ids
57+
end
58+
5259
private
5360

5461
def exists_query_start(condition)

spec/e2e/query_proxy_methods_spec.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,34 @@ def destroy_called
444444
end
445445
end
446446

447+
describe 'ids' do
448+
before(:each) do
449+
[Student, Lesson].each(&:delete_all)
450+
451+
@john = Student.create(name: 'John')
452+
@history = Lesson.create(name: 'history')
453+
@math2 = Lesson.create(name: 'math2')
454+
@john.lessons << @history
455+
@john.lessons << @math2
456+
end
457+
458+
it 'returns the ids of nodes on the class' do
459+
expect(Lesson.ids).to match_array([@history.id, @math2.id])
460+
end
461+
462+
it 'returns the ids of nodes on a query proxy association' do
463+
expect(@john.lessons.ids).to match_array([@history.id, @math2.id])
464+
end
465+
466+
it 'returns the ids of nodes on a where chain' do
467+
expect(Lesson.where(name: 'history').ids).to eq([@history.id])
468+
end
469+
470+
it 'returns an empty array when there are no matches' do
471+
expect(Lesson.where(name: 'nope').ids).to eq([])
472+
end
473+
end
474+
447475
describe 'distinct' do
448476
let(:frank) { Student.create(name: 'Frank') }
449477
let(:bill) { Teacher.create(name: 'Bill') }

0 commit comments

Comments
 (0)