pg_search
pg_search copied to clipboard
Filtering Multi-search Results
I'm moving from using search scopes to multi-search because of performance issue when searching associations.
I have a search bar and and 3 optional filters to filter the results. The 3 filters are scopes that use joins for the association.
For example:
scope :filter_by_office_user, ->(office_user) { left_outer_joins(:office).where(office: { user_assigned: office_user }) }
scope :filter_by_office_territory, ->(office_territory) { left_outer_joins(:office).where(office: { territory: office_territory }) }
scope :filter_by_office_speciality, ->(office_speciality) { left_outer_joins(:office).where(office: { speciality: office_speciality }) }
The search uses a scope as well:
scope :filter_by_search, ->(search) { PgSearch.multisearch(search) }
Here is the physician controller search action:
@physicians = Physician.where(nil)
filtering_params(params).each do |key, value|
@physicians = @physicians.public_send("filter_by_#{key}", value) if value.present?
end
@pagy, @physicians = pagy(@physicians, items: 10, link_extra: 'data-remote="true"')
I'm under the impression that since I'm now using the search document table, I can now simplify my scopes to only search within the search document table and I don't need to use joins anymore.
I've built my search document to include results from my association.
The issues I've ran into:
Leaving the search blank/empty, won't return all results and instead throws:
ActionView::Template::Error (undefined method 'searchable'
Changing my scopes to use PgSearch.multisearch
scope :filter_by_office_user, ->(office_user) { PgSearch.multisearch(office_user) }
This does work by itself but I can't chain to further filter the results. For example, if I filter by office_user and then territory, I end up getting this error:
NoMethodError (undefined method `filter_by_office_territory'
I'd be grateful on any help figuring a better approach to filtering results.