Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
pg_search + Rails - Prevent redirect to page with search results if there wasnt't any of them

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!