Skip to content

Commit

Permalink
push a joins attribute to the facet
Browse files Browse the repository at this point in the history
  • Loading branch information
phoet committed Sep 26, 2018
1 parent 9ef15eb commit 74b82f2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/forty_facets/filter/sql_facet_filter_definition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ def initialize(search, queries, opts)
@search = search
@queries = queries
@path = Array(opts[:path]) if opts[:path].present?
@joins = Array(opts[:joins]) if opts[:joins].present?
@path ||= @queries.keys
@options = opts
end
Expand All @@ -29,7 +30,7 @@ def build_scope
Proc.new do |base|
# intersection of values and definition queries
base.where(selected_queries.values.map do |query|
"(#{query})"
"(#{query})"
end.join(" OR "))
end
end
Expand All @@ -55,13 +56,14 @@ def add(value)

def facet
query = definition.queries.map do |key, sql_query|
"(#{sql_query}) as #{key}"
"(#{sql_query}) as #{key}"
end.join(", ")
query += ", count(*) as occurrences"

counts = without.result.reorder("")
.select(query)
.group(definition.queries.keys)
counts = counts.joins(definition.joins) if definition.joins
counts.includes_values = []

result = {}
Expand Down
8 changes: 8 additions & 0 deletions test/smoke_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ class MovieSearch < FortyFacets::FacetSearch
facet [:studio, :country], name: 'Country'
facet [:studio, :status], name: 'Studio status'
facet [:studio, :producers], name: 'Producers'
sql_facet({ uschis: "studios.name = 'Uschi'", non_uschis: "studios.name != 'USCHI'" },
{ name: "Uschis", path: [:studio, :uschis], joins: [:studio] })
sql_facet({ classic: "year <= 1980", non_classic: "year > 1980" },
{ name: "Classic", path: :classic })
sql_facet({ classic: "year <= 1980", non_classic: "year > 1980" },
Expand All @@ -34,6 +36,12 @@ class MovieSearch < FortyFacets::FacetSearch

class SmokeTest < Minitest::Test

def test_sql_facet_with_belongs_to
search = MovieSearch.new({'studio-uschis' => {}})
assert_equal Movie.count, search.result.size
assert_equal search.filter([:studio, :uschis]).facet, [FortyFacets::FacetValue.new(:uschis, 0, false), FortyFacets::FacetValue.new(:non_uschis, 40, false)]
end

def test_it_finds_all_movies
search = MovieSearch.new({})
assert_equal Movie.all.size, search.result.size
Expand Down

1 comment on commit 74b82f2

@axelerator
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❤️

Please sign in to comment.