Search code examples
ruby-on-railsrubyactiverecordpgpg-search

How to filter results by their associations when using PG search gem?


I am using PG search gem in my Rails app. Say I get a set of articles in my controller:

@articles = Article.search(params[:search]).with_pg_search_highlight

the problem with PG search here is that I get back an array, instead of AR object. So now I cannot do something like

@research_articles = @articles.where(category: 'research')

Because I will get a

undefined method `where' for Array

Now I can make several queries from that one action, but what would be a better solution to this problem?


Solution

  • What about changing the chain?

    @articles = Article.where(category: 'research').search(params[:search]).with_pg_search_highlight
    

    EDIT:

    A way without making 2 queries would be:

    @found_articles = Article.search(params[:search]).with_pg_search_highlight
    @research_articles = @found_articles.select { |article| article.category == "research" }