Reputation: 7043
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?
Upvotes: 1
Views: 1776
Reputation: 202
pg_search gem provides pg_search_scope.
See the doc https://github.com/Casecommons/pg_search#pg_search_scope
You can also chain where condition with pg_search_scope.
Upvotes: 2
Reputation: 4413
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" }
Upvotes: 1
Reputation: 121000
You probably should define a scope (or even simple getter would be enough here) and reuse it:
def simple_search
pure = Article.search(params[:search])
(block_given? ? yield(pure) : pure).with_pg_search_highlight
end
And then:
@articles = simple_search
@research_articles = simple_search { |ss| ss.where(category: 'research') }
Upvotes: 1