Skip to content

Commit 1a2cf36

Browse files
committed
Add call-able :scope option to Field::HasMany
1 parent 5607daf commit 1a2cf36

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
@@ -106,12 +106,11 @@ def includes
106106
end
107107

108108
def candidate_resources
109-
if options.key?(:includes)
110-
includes = options.fetch(:includes)
111-
associated_class.includes(*includes).all
112-
else
113-
associated_class.all
114-
end
109+
scope = options[:scope] ? options[:scope].call(self) : associated_class.all
110+
scope = scope.includes(*options.fetch(:includes)) if options.key?(:includes)
111+
112+
order = options.delete(:order)
113+
order ? scope.reorder(order) : scope
115114
end
116115

117116
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
@@ -289,4 +289,56 @@
289289
end
290290
end
291291
end
292+
293+
describe "#associated_resource_options" do
294+
context "with `order` option" do
295+
it "returns the resources in correct order" do
296+
order = create(:order)
297+
create_list(:customer, 5)
298+
options = {order: "name"}
299+
association = Administrate::Field::HasMany.with_options(options)
300+
301+
field = association.new(:customer, [], :show, resource: order)
302+
303+
correct_order = Customer.order("name").pluck(:id)
304+
305+
resources = field.associated_resource_options.compact.to_h.values
306+
expect(resources).to eq correct_order
307+
end
308+
309+
it "ignores the order passed in `scope`" do
310+
order = create(:order)
311+
create_list(:customer, 3)
312+
options = {
313+
order: "name",
314+
scope: ->(_field) { Customer.order(name: :desc) }
315+
}
316+
association = Administrate::Field::HasMany.with_options(options)
317+
318+
field = association.new(:customer, [], :show, resource: order)
319+
320+
correct_order = Customer.order("name").pluck(:id)
321+
322+
resources = field.associated_resource_options.compact.to_h.values
323+
expect(resources).to eq correct_order
324+
end
325+
end
326+
327+
context "with `scope` option" do
328+
it "returns the resources within the passed scope" do
329+
# Building instead of creating, to avoid a dependent customer being
330+
# created, leading to random failures
331+
order = build(:order)
332+
333+
1.upto(3) { |i| create :customer, name: "customer-#{i}" }
334+
scope = ->(_field) { Customer.order(name: :desc).limit(2) }
335+
336+
association = Administrate::Field::HasMany.with_options(scope: scope)
337+
field = association.new(:customer, [], :show, resource: order)
338+
resources = field.associated_resource_options.compact.to_h.keys
339+
340+
expect(resources).to eq ["customer-3", "customer-2"]
341+
end
342+
end
343+
end
292344
end

0 commit comments

Comments
 (0)