Skip to content

Commit 1eb4401

Browse files
committed
Add call-able :scope option to Field::HasMany
1 parent 0ac5e3c commit 1eb4401

File tree

2 files changed

+57
-6
lines changed

2 files changed

+57
-6
lines changed

lib/administrate/field/has_many.rb

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -97,12 +97,11 @@ def includes
9797
end
9898

9999
def candidate_resources
100-
if options.key?(:includes)
101-
includes = options.fetch(:includes)
102-
associated_class.includes(*includes).all
103-
else
104-
associated_class.all
105-
end
100+
scope = options[:scope] ? options[:scope].call(self) : associated_class.all
101+
scope = scope.includes(*options.fetch(:includes)) if options.key?(:includes)
102+
103+
order = options.delete(:order)
104+
order ? scope.reorder(order) : scope
106105
end
107106

108107
def display_candidate_resource(resource)

spec/lib/fields/has_many_spec.rb

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,4 +299,56 @@
299299
end
300300
end
301301
end
302+
303+
describe "#associated_resource_options" do
304+
context "with `order` option" do
305+
it "returns the resources in correct order" do
306+
order = create(:order)
307+
create_list(:customer, 5)
308+
options = {order: "name"}
309+
association = Administrate::Field::HasMany.with_options(options)
310+
311+
field = association.new(:customer, [], :show, resource: order)
312+
313+
correct_order = Customer.order("name").pluck(:id)
314+
315+
resources = field.associated_resource_options.compact.to_h.values
316+
expect(resources).to eq correct_order
317+
end
318+
319+
it "ignores the order passed in `scope`" do
320+
order = create(:order)
321+
create_list(:customer, 3)
322+
options = {
323+
order: "name",
324+
scope: ->(_field) { Customer.order(name: :desc) }
325+
}
326+
association = Administrate::Field::HasMany.with_options(options)
327+
328+
field = association.new(:customer, [], :show, resource: order)
329+
330+
correct_order = Customer.order("name").pluck(:id)
331+
332+
resources = field.associated_resource_options.compact.to_h.values
333+
expect(resources).to eq correct_order
334+
end
335+
end
336+
337+
context "with `scope` option" do
338+
it "returns the resources within the passed scope" do
339+
# Building instead of creating, to avoid a dependent customer being
340+
# created, leading to random failures
341+
order = build(:order)
342+
343+
1.upto(3) { |i| create :customer, name: "customer-#{i}" }
344+
scope = ->(_field) { Customer.order(name: :desc).limit(2) }
345+
346+
association = Administrate::Field::HasMany.with_options(scope: scope)
347+
field = association.new(:customer, [], :show, resource: order)
348+
resources = field.associated_resource_options.compact.to_h.keys
349+
350+
expect(resources).to eq ["customer-3", "customer-2"]
351+
end
352+
end
353+
end
302354
end

0 commit comments

Comments
 (0)