pg_search 不返回单个字段的结果

Rya*_*acG 2 ruby-on-rails-3 pg-search

我有一个“资产”模型的搜索页面,除了搜索“serial_no”字段特定的任何内容之外,一切都工作正常。

资产.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
Run Code Online (Sandbox Code Playgroud)

例如,我有一个序列号为 Z21313412A 的资产,但当我搜索“Z”时,没有返回结果。几周来我一直在尝试解决这个问题,但没有成功。

Mur*_*foX 5

根据文档

\n\n
PostgreSQL\xe2\x80\x99s full text search matches on whole words by default. \nIf you want to search for partial words, however, you can set :prefix to true. \nSince this is a :tsearch-specific option, you should pass it to :tsearch \ndirectly, as shown in the following example.\n
Run Code Online (Sandbox Code Playgroud)\n\n

也许添加:prefix到您的配置可以解决问题。
\nGithub 页面的示例:

\n\n
pg_search_scope :whose_name_starts_with,\n              :against => :name,\n              :using => {\n                :tsearch => {:prefix => true}\n              }\n
Run Code Online (Sandbox Code Playgroud)\n