rails pg_search поиск по ассоциации

у меня 3 модели

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 и изменяю класс 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}%")

person Alex    schedule 22.10.2020    source источник


Ответы (1)


вы можете попробовать так:

# 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")
person Palash Bera    schedule 22.10.2020
comment
Хорошо, но PG находит столбец searchable в таблице AlbumStat. PG::UndefinedColumn: ERROR: column album_stats.searchable does not exist - person Alex; 23.10.2020