Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

255
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda