rails pg_search search in association

1k views Asked by At

I Have 3 models

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

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

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?

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

There are 1 answers

1
Palash Bera On

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")