简体   繁体   English

rails pg_search 关联搜索

[英]rails pg_search search in association

I Have 3 models我有3个模型

class Site
  has_many :album_stats
end

class Album
  has_many :album_stats
end

class AlbumStat
  belongs_to :album
  belongs_to :site
end

Before Pg_search i searched like this在 Pg_search 之前我是这样搜索的

site = Site.first
site.album_stats.left_joins(:album).where('albums.tag LIKE ? or albums.title LIKE ?', "%#{@tag}%", "%#{@tag}%")

Now i am add pg_search gem and modify Album class现在我添加 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 } }

Search in album model works fine, but how can i modify my old query, to search through pg_search?在专辑模型中搜索工作正常,但如何修改旧查询以通过 pg_search 进行搜索?

site.album_stats.left_joins(:album).where('albums.tag LIKE ? or albums.title LIKE ?', "%#{@tag}%", "%#{@tag}%")

you can try like this:你可以这样尝试:

# 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

Now, you can modify your query like this:现在,您可以像这样修改您的查询:

site.album_stats.album_search("Your Value")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM