Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

261
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda