pg_search icon indicating copy to clipboard operation
pg_search copied to clipboard

How to include/eager_load associations from additional attributes?

Open jcohenho opened this issue 4 years ago • 2 comments

In the docs, you can eager load the searchable associations via PgSearch.multisearch("Square").includes(:searchable).

After adding additional attributes via migrations and configuration:

   # migration file
   create_table :pg_search_documents do |t|
     t.text :content
     t.references :author, index: true
     t.belongs_to :searchable, polymorphic: true, index: true
     t.timestamps null: false
   end

  # model.rb
  multisearchable(
    against: [:title, :body],
    additional_attributes: -> (article) { { author_id: article.author_id } }
  )

I now have the ability to do:

PgSearch.multisearch(params['search']).where(author_id: 2)

However, I would like to also eager load the Authors association to prevent n+1 queries, but it doesn't seem like this is possible. I've tried PgSearch.multisearch(params['search']).includes(:searchable, :author).where(author_id: 2) but this gives a missing association error. Any suggestions?

jcohenho avatar Jul 07 '21 14:07 jcohenho

@nertzy any insights here?

jcohenho avatar Jul 20 '21 21:07 jcohenho

Did you add author association to the model?

AlexChuv avatar Oct 13 '21 17:10 AlexChuv