Search code examples
ruby-on-railsrubydevisepg-search

Customize pg_search to only show current user's content


I have a multiuser site, and I want users to be able to full-text multi-model search only their own content.

My Work model belongs_to: :users. Here's a snippet of work.rb :

class Work < ApplicationRecord
  include PgSearch
  belongs_to :user
  …

The ideal scenario would be something like this in my controller:

@results = PgSearch.multisearch('spring').where(:_user_id => current_user.id)

I was able to easily do this using the Searchkick gem with Elasticsearch by using this line of code:

@results = Searchkick.search query, where: {user_id: current_user.id}

I can't use Elasticsearch anymore unfortunately.

How can I implement similar functionality in pg_search?

Thanks a lot


Solution

  • I am just starting to work with PgSearch, but based on what I see, you can only apply filters on what data gets sent into their database pg_search_documents. So you cannot isolate on a particular user for the search that you do later. They simply concat the various fields into their content field and reference the model and record they came from. This allows easy searches to find the records which match the criteria, but then you have to post process the data.

    To do what you're suggesting would require creating a search table for each user.

    if you include the user_id in your against criteria (should be in the content), then you can post process the data quickly since the ID will be in the content. If it is at the end of the :against list, it will be at the end of the content, so you can strip it off quickly and process against it