Filtering
Filters are usually one-liners, with the logic delegated to an Adapter.
You can view allow_filter
like a whitelist. We wouldn’t want to
automatically support filters - otherwise sneaky users might filter our
Employee
s to only those making a certain salary. Hence the whitelist.
To customize a filter:
A real-life example might be a prefix query:
Filtering Relationships
Prefix the filter parameter with the relevant JSONAPI Type like so:
Default Filters
You may want your scope to be filtered any time it is accessed - Perhaps
you only want to show active
posts by default:
Default filters can be overridden if there is a corresponding
allow_filter
. Given a Resource
:
And the following requests:
The first will display only active posts, the second will display only inactive posts.
Filter Conventions
There are some common naming conventions for supporting more complex filters:
NOTE: AND queries are supported by default - just pass a comma-delimited list of values.
Filter Guards
You can conditionally allow filters based on runtime context. Let’s say only managers should be allowed to filter employees by salary:
Filter Aliases
Aliases mostly come into play when supporting backwards
compatibility. Let’s say we originally called the filter fname
then
later wanted the more-expressive first_name
. An alias allows is to
keep a one-liner with the correct naming, while still responding correctly
to fname
:
Accessing Runtime Context
allow_filter
can access runtime context (in Rails, the controller) as
the last argument: