Appreciate for a help. I'm using Rails 4, ruby 2.2.3 and PostgreSQL 9.6. I have website with search based on pg_search, and it works perfectly with multiple models:
/app/models/event.rb:
multisearchable against: [:title, :subtitle]
Both searchable models and search controller setted up very simple by official manuals.
/app/controllers/results_controller.rb:
class ResultsController < FrontendController
def index
@search_results = PgSearch.multisearch(params[:query])
end
end
And my results view:
/app/views/results/index.slim:
.search-results-wrap
- @search_results.each do |pg_search_document|
#showing title of each result, etc.
Now I need to improve it by checking before redirect to page with search results - are there any results at all? I mean, there isn't much sense in redirecting if there are no results and it will be more smart to just show a flash message(or something like that) "sorry, no results" on current page.
Is there possible ways to do it?
Something like this?
if (<your search function>).empty?
flash.now[:notice] = "No, results"
render '<your current search page>'
else
redirect_to '<your search results page>'
end
I recommend using the model approach
Article.rb
def self.search(query)
if query.present?
search_for(query) # takes you to your search method
else
# No query? Return all records, newest first.
Article.all.order('updated_at DESC')
end
end
pg_search_scope :search_for,
...
Article index or search search results page
- if @articles.present?
# Show articles
- else
p No articles found. Use other queries
Controller
def index
@articles = Article.search(params[:query])
Best practice is to always tell the user whether he is getting any results or if he made a typo or needs to look things up differently.