Raise Ransack::InvalidSearchError instead of ArgumentError on unknown conditions #1543
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Currently, when Ransack encounters invalid search attributes (those not included in
ransackable_attributes
) while usingModel.ransack!()
it raises a genericArgumentError
. This makes it difficult to provide helpful feedback to an API consumer that their search params are incorrect.This PR adds a custom exception type
Ransack::InvalidSearchError
and raises it instead ofArgumentError
in cases where there are invalid attributes used in a search.✅ Backwards compatible
The solution in this PR should be perfectly backwards compatible. The new error inherits from ArgumentError, and the test cases assert this.
Problem
Assume I have the following code in my controller
As a result this will return 5xx to the consumer. But since this is a user error, i want to return 4xx.
I could fix this by adding the following:
but the problem is that I have to add this everywhere in my controllers.
I could make this cleaner by having a helper, for example defining a
rescuable_ransack
method to extend active record e.g:then using
rescuable_ransack
in my controllers:then add something to my application controller to catch all such exceptions:
which would work, but this also seems pretty useful to have in ransack itself. Hence this suggestion to add it to the library.
Proposed Solution
Add a specialized exception class (e.g.,
Ransack::InvalidSearchError
) that would be raised in cases whereignore_unknown_conditions
currently raises anArgumentError
. This would then allow me to add something in my ApplicationController like the following:This would be a very concise way to catch and handle such problems in controller actions.