ActiveSearch :: EmptyTermError
I am using the Active_Search plugin to try and add some simple search functions to the application, it works fine when something is found in the DB, but if I just run the search without typing, it gives me the error "ActiveSearch :: EmptyTermError" ...
How do I get the search action to return the correct values (which it can do), but also if nothing is found or nothing is entered, the application tells me this with flash.
Here is the code:
def search
if params [: query]
query = params [: query]
@users = User.find_using_term (query)
else #ie nothing is found in the query so do this
flash [: notice] = "No Results Found"
redirect_to: action => "home"
end
end
Any ideas would be greatly appreciated, thanks.
You should handle the error using a block rescue
:
def search
@users = User.find_using_term params[:query]
rescue ActiveSearch::EmptyTermError
flash[:notice] = "No Results Found"
redirect_to :action => "home"
end
This way, if the search went well but the result set is still empty, you will not be redirected. Here's some code that blinks and redirects you to both empty results and EmptyTermError.
def search
@users = User.find_using_term params[:query]
return unless @users.empty?
rescue ActiveSearch::EmptyTermError
ensure
flash[:notice] = "No Results Found"
redirect_to :action => "home"
end
return
just goes away if we have results.
The block is rescue
empty, it just skips the error.
And the block ensure
whether we start handling the exception or not. (But of course not if we go back before it.)
a source to share