Class: Spree::SearchProvider::Database

Inherits:
Base
  • Object
show all
Defined in:
app/models/spree/search_provider/database.rb

Constant Summary collapse

CUSTOM_SORT_SCOPES =
{
  'price' => :ascend_by_price,
  '-price' => :descend_by_price,
  'best_selling' => :by_best_selling
}.freeze

Instance Attribute Summary

Attributes inherited from Base

#store

Instance Method Summary collapse

Methods inherited from Base

#ensure_index_settings!, #index, #index_batch, indexing_required?, #initialize, #reindex, #remove, #remove_by_id

Constructor Details

This class inherits a constructor from Spree::SearchProvider::Base

Instance Method Details

#filters(scope:, query: nil, filters: {}) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/models/spree/search_provider/database.rb', line 33

def filters(scope:, query: nil, filters: {})
  filters = filters.is_a?(Hash) ? filters.dup : {}
  category = filters.delete('_category') || filters.delete(:_category)
  option_value_ids = Array(filters.delete('with_option_value_ids') || filters.delete(:with_option_value_ids))

  # Apply text search + ransack filters (without option values)
  scope_before_options = apply_search_and_filters(scope, query: query, filters: filters)

  # Apply option value filters for the final scope
  scope_with_options = if option_value_ids.present?
                         scope_before_options.with_option_value_ids(option_value_ids)
                       else
                         scope_before_options
                       end

  filter_facets = build_facets(scope_with_options, category: category, option_value_ids: option_value_ids, scope_before_options: scope_before_options)

  FiltersResult.new(
    filters: filter_facets[:filters],
    sort_options: filter_facets[:sort_options],
    default_sort: filter_facets[:default_sort],
    total_count: filter_facets[:total_count]
  )
end

#search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'app/models/spree/search_provider/database.rb', line 10

def search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)
  filters = filters.is_a?(Hash) ? filters.dup : {}
  option_value_ids = filters.delete('with_option_value_ids') || filters.delete(:with_option_value_ids)

  scope = apply_search_and_filters(scope, query: query, filters: filters)
  scope = scope.with_option_value_ids(Array(option_value_ids)) if option_value_ids.present?

  # Total count (before sorting to avoid computed column conflicts with count)
  total = scope.distinct.count

  # Sorting + pagination
  scope = apply_sort(scope, sort)
  page = [page.to_i, 1].max
  limit = limit.to_i.clamp(1, 100)
  products = scope.offset((page - 1) * limit).limit(limit)

  SearchResult.new(
    products: products,
    total_count: total,
    pagy: build_pagy(total, page, limit)
  )
end