Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to validate search string without making query #33

Closed
bpatram opened this issue Feb 26, 2017 · 3 comments
Closed

Ability to validate search string without making query #33

bpatram opened this issue Feb 26, 2017 · 3 comments

Comments

@bpatram
Copy link

bpatram commented Feb 26, 2017

Is there a way to validate a search string/query for a specific search scope?

For example if I have a search_scope of the following:

# my_model.rb MyModel
search_scope :search do
  attributes :value # value is an integer attribute type (not string)
  options :value, default: true
end

It would be nice to be able to call something like MyModel.validate_search("value:Foo") which would not actually make a query to the database but either raise an error (like theIncompatibleDatatype error) or return a boolean value.

This would allow us to validate/verify queries before being run and handle errors rather than silently failing when calling search("value:Foo") as it does now. The unsafe_search method is nice, but if there was a way to separate validation from querying that would be great.

My primary reason for this request is to better handle errors when using custom filters in the jsonapi_resources gem which has a custom verify method.

@bpatram
Copy link
Author

bpatram commented Feb 26, 2017

After digging into the code this may seem fairly trivial to add to the SearchCop module as another ClassMethod. Unfortunately I don't think I'll have the time to make a proper PR this weekend.

# raises an error or returns the query
def validate_search_scope(query, scope_name)
  QueryBuilder.new(self, query, search_scopes[scope_name])
  query
end

@mrkamel
Copy link
Owner

mrkamel commented Feb 27, 2017

sounds reasonable, i'll take a look at it asap.

@mrkamel
Copy link
Owner

mrkamel commented Feb 28, 2017

Well, you actually can simply do MyModel.unsafe_search("query").to_sql or MyModel.unsafe_search("query"). As SearchCop returns an AR::Relation the query of course gets lazily evaluated. So i'm not sure adding validate_search_cop! provides much benefit.

@mrkamel mrkamel closed this as completed Mar 8, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants