我有三种型号的
class Site
has_many :album_stats
end
class Album
has_many :album_stats
end
class AlbumStat
belongs_to :album
belongs_to :site
end
在Pg_search之前,我像这样搜索
site = Site.first
site.album_stats.left_joins(:album).where('albums.tag LIKE ? or albums.title LIKE ?', "%#{@tag}%", "%#{@tag}%")
现在我添加pg_search gem并修改Album
类
class Album
include PgSearch::Model
pg_search_scope :search,
against: %i[title tag],
using: { tsearch: { dictionary: 'english', tsvector_column: 'searchable', any_word: true } }
在相册模型中搜索很好,但我如何修改我的旧查询,通过pg_Search进行搜索?
site.album_stats.left_joins(:album).where('albums.tag LIKE ? or albums.title LIKE ?', "%#{@tag}%", "%#{@tag}%")
您可以这样尝试:
# app/models/album_set.rb
class AlbumStat
include PgSearch::Model
belongs_to :album
belongs_to :site
pg_search_scope :album_search,
associated_against: { album: [:tag, :title] },
using: {
tsearch: {
dictionary: 'english',
tsvector_column: 'searchable',
any_word: true
}
}
end
现在,您可以这样修改您的查询:
site.album_stats.album_search("Your Value")