Skip to content

Commit

Permalink
add display name method, support multiword search
Browse files Browse the repository at this point in the history
  • Loading branch information
dougcole committed Mar 28, 2018
1 parent feec603 commit 259ac9d
Show file tree
Hide file tree
Showing 5 changed files with 13 additions and 6 deletions.
2 changes: 1 addition & 1 deletion app/controllers/search_controller.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class SearchController < ApplicationController
def index
result = ContestSearch.search(params[:q]).limit(4)
hash_results = result.map {|r| {id: r.id, text: r.name} }
hash_results = result.map {|r| {id: r.id, text: r.display_name} }
render json: { "results": hash_results }
end
end
2 changes: 1 addition & 1 deletion app/models/candidate.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class Candidate < ApplicationRecord
belongs_to :contest

def name
def display_name
primary_name
end
end
4 changes: 4 additions & 0 deletions app/models/contest.rb
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
class Contest < ApplicationRecord

def display_name
"#{name} - #{electoral_district_name}"
end
end
9 changes: 6 additions & 3 deletions app/models/contest_search.rb
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
class ContestSearch
def self.search(query)

columns = %w(primary_office_name secondary_office_name electoral_district_name)
tsvector = to_tsvector(columns)
results = Contest.where("to_tsvector(#{tsvector}) @@ to_tsquery('english', ?)", query + ":*")
results = Contest.where("to_tsvector(#{tsvector}) @@ to_tsquery('english', ?)", to_tsquery(query))

if results.empty?
columns = %w(primary_name primary_party secondary_name)
tsvector = to_tsvector(columns)
results = Candidate.where("to_tsvector(#{tsvector}) @@ to_tsquery('english', ?)", query + ":*")
results = Candidate.where("to_tsvector(#{tsvector}) @@ to_tsquery('english', ?)", to_tsquery(query))
end

results
Expand All @@ -17,4 +16,8 @@ def self.search(query)
def self.to_tsvector(columns)
columns.map {|c| "coalesce(#{c}, '')" }.join(" || ' ' || ")
end

def self.to_tsquery(query)
res = query.split(' ').map {|q| "#{q}:*" }.join(" & ")
end
end
2 changes: 1 addition & 1 deletion app/views/questions/_question.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<div class="text-center">votes</div>
</div>
<div class="col">
Question for: <%= question.contest.name -%><br />
Question for: <%= question.contest.display_name -%><br />
<%= question.body -%>
</div>
</div>

0 comments on commit 259ac9d

Please sign in to comment.