Skip to content

Commit 7b73952

Browse files
authored
Merge pull request #756 from lgebhardt/default_sort_params
Default Sort
2 parents 2ae00f7 + 7f5c271 commit 7b73952

4 files changed

Lines changed: 27 additions & 2 deletions

File tree

README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,21 @@ The request will look something like:
333333
GET /books?include=author&sort=author.name
334334
```
335335

336+
###### Default sorting
337+
338+
By default JR sorts ascending on the `id` of the primary resource, unless the request specifies an alternate sort order.
339+
To override this you may override the `self.default_sort` on a `resource`. `default_sort` should return an array of
340+
`sort_param` hashes. A `sort_param` hash contains a `field` and a `direction`, with `direction` being either `:asc` or
341+
`:desc`.
342+
343+
For example:
344+
345+
```ruby
346+
def self.default_sort
347+
[{field: 'name_last', direction: :desc}, {field: 'name_first', direction: :desc}]
348+
end
349+
```
350+
336351
##### Attribute Formatting
337352

338353
Attributes can have a `Format`. By default all attributes use the default formatter. If an attribute has the `format`

lib/jsonapi/request_parser.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def initialize(params = nil, options = {})
1616
@operations = []
1717
@fields = {}
1818
@filters = {}
19-
@sort_criteria = [{ field: 'id', direction: :asc }]
19+
@sort_criteria = nil
2020
@source_klass = nil
2121
@source_id = nil
2222
@include_directives = nil

lib/jsonapi/resource.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -861,11 +861,17 @@ def module_path
861861
end
862862
end
863863

864+
def default_sort
865+
[{field: 'id', direction: :asc}]
866+
end
867+
864868
def construct_order_options(sort_params)
869+
sort_params ||= default_sort
870+
865871
return {} unless sort_params
866872

867873
sort_params.each_with_object({}) do |sort, order_hash|
868-
field = sort[:field] == 'id' ? _primary_key : sort[:field]
874+
field = sort[:field].to_s == 'id' ? _primary_key : sort[:field].to_s
869875
order_hash[field] = sort[:direction]
870876
end
871877
end

test/fixtures/active_record.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1237,6 +1237,10 @@ class PostResource < JSONAPI::Resource
12371237
has_one :section
12381238
has_many :comments, acts_as_set: false
12391239

1240+
def self.default_sort
1241+
[{field: 'title', direction: :asc}, {field: 'id', direction: :desc}]
1242+
end
1243+
12401244
def subject
12411245
@model.title
12421246
end

0 commit comments

Comments
 (0)