Question

I am using pg_search for fulltext search, it works fine when I type a search term, but when I give it a empty string I expect it to return all models, instead I get no results.

How can I configure pg_search_scope to return all models on empty search?

Thank you

Was it helpful?

Solution

Here's my answer from https://github.com/Casecommons/pg_search/issues/49


I don't think that having an empty query should always trigger all records, for a couple reasons.

First, I don't think that there is a well-defined order to return records in. (The usual sorting by search rank is meaningless without a query)

Second, I think that the database should define how the various search features treat a blank string, so that all of the logic lives in just one place.

So, I want to offer this workaround, which I think will work out better for your situation.

class MyModel < ActiveRecord::Base
  include PgSearch

  pg_search_scope :search_by_name, :against => :name

  def self.search(query)
    if query.present?
      search_by_name(query)
    else
      # No query? Return all records, newest first.
      order("created_at DESC")
    end
  end
end

This solution should still be chainable, so you can call something like this in your controller safely (assuming you're using a pagination library like kaminari.

MyModel.where(:published => true).search(params[:query]).page(params[:page])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top