Skip to content

Commit 8693902

Browse files
Update docs for dynamic sorting
1 parent 36e98fc commit 8693902

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,38 @@ But since we're devout followers of the SOLID principles, we can define a sort c
142142
which returns the sorted collection. Under the hood the sort class is initialized with the current scope and the
143143
direction parameter.
144144
145+
#### Dynamic sorting (prefix-based)
146+
147+
Sometimes you want to allow sorting by a dynamic subset of attributes that share a common prefix (e.g., JSON/JSONB keys, translated columns, join records). You can register a dynamic sort by attribute prefix using `dynamically_sorts_by`.
148+
149+
- The configured prefix is matched against each parsed sort attribute.
150+
- The prefix is stripped and only the dynamic part is passed to your sort handler.
151+
- You can provide either a lambda/proc or a class. The callable receives `(collection, dynamic_attribute, direction)`.
152+
153+
Example with a lambda (PostgreSQL JSONB text value):
154+
155+
```ruby
156+
# Allows sorting by any key in the `data` column: e.g. sort=-data.name,data.created_at
157+
dynamically_sorts_by :'data.', ->(collection, attribute, direction) {
158+
# attribute is the part after the prefix, e.g. "name" or "created_at"
159+
quoted_attribute = ActiveRecord::Base.connection.quote(attribute)
160+
collection.order(Arel.sql("(data->>#{quoted_attribute}) #{direction}"))
161+
}
162+
```
163+
164+
Example with a sort class (PostgreSQL JSONB text value):
165+
166+
```ruby
167+
class DataSort < Jsonapi::QueryBuilder::DynamicSort
168+
def results
169+
quoted_attribute = ActiveRecord::Base.connection.quote(dynamic_attribute)
170+
collection.order(Arel.sql("(data->>#{quoted_attribute}) #{direction}"))
171+
end
172+
end
173+
174+
dynamically_sorts_by :'data.', DataSort
175+
```
176+
145177
### Filtering
146178
147179
#### Simple exact match filters

0 commit comments

Comments
 (0)