Question

I've got a search page for my "assets" model and everything works fine apart from searching for anything specific to the "serial_no" field.

Asset.rb

# == Schema Information
#
# Table name: assets
#
#  id                :integer         not null, primary key
#  asset_description :string(255)
#  asset_type        :string(255)
#  status            :string(255)
#  serial_no         :string(255)
#  user_id           :integer
#  cost              :decimal(, )
#  barcode           :string(255)
#  comment           :string(255)
#  date_purchased    :date
#  created_at        :datetime        not null
#  updated_at        :datetime        not null
#
class Asset < ActiveRecord::Base
  attr_accessible :asset_description, :asset_type, :comment, 
  :date_purchased, :serial_no, :status, :user_id, :cost, :barcode
  belongs_to :user
  validates  :user_id, presence: true
  validates  :asset_description, presence: true
  validates  :asset_type, presence: true
  validates  :serial_no, presence: true, uniqueness: true
  validates  :status, presence: true
  validates  :comment, length: { maximum: 150 }

  include PgSearch
  pg_search_scope :search, against: [:asset_description, :status, :asset_type, 
    :comment, :cost, :serial_no, :date_purchased],
   using: {tsearch: { dictionary: "english" }},
   associated_against: { user: :name }

  #older assets first
  default_scope order: 'assets.created_at ASC'

  def self.text_search(query)
    if query.present?
      search(query)
    else
      scoped 
    end
  end
end

For example, I have an asset with the serial_no: Z21313412A but when I search for "Z" no results are returned. I've been trying to fix this for a couple of weeks but have had no luck.

Was it helpful?

Solution

Acording to the documentation:

PostgreSQL’s full text search matches on whole words by default. 
If you want to search for partial words, however, you can set :prefix to true. 
Since this is a :tsearch-specific option, you should pass it to :tsearch 
directly, as shown in the following example.

Maybe adding :prefix to your configuration solves the problem.
Example from the Github page:

pg_search_scope :whose_name_starts_with,
              :against => :name,
              :using => {
                :tsearch => {:prefix => true}
              }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top