Split Poll::Booth.search in two methods

We use this method in two different scenarios. In an AJAX request, we
don't want to return every booth if the search is blank. However, in a
normal HTTP GET request, we want to return every record when the search
is empty, as we do everywhere else.

It's possible the behaviour of the AJAX call is unusual, since it
searches all booths, and not just the ones assigned to a poll. If we
changed this behaviour, we could simplify the code and remove the
`quick_search` method.
This commit is contained in:
Javi Martín
2019-10-01 02:19:41 +02:00
parent 24e4f4518f
commit 710a1d8357
4 changed files with 31 additions and 4 deletions

View File

@@ -9,7 +9,7 @@ class Admin::Poll::BoothAssignmentsController < Admin::Poll::BaseController
def search_booths
load_search
@booths = ::Poll::Booth.search(@search)
@booths = ::Poll::Booth.quick_search(@search)
respond_to do |format|
format.js
end

View File

@@ -2,7 +2,7 @@ class Admin::Poll::BoothsController < Admin::Poll::BaseController
load_and_authorize_resource class: "Poll::Booth"
def index
@booths = @booths.search params[:search] if params[:search]
@booths = @booths.search(params[:search])
@booths = @booths.order(name: :asc).page(params[:page])
end

View File

@@ -7,10 +7,17 @@ class Poll
validates :name, presence: true, uniqueness: true
def self.search(terms)
return Booth.none if terms.blank?
Booth.where("name ILIKE ? OR location ILIKE ?", "%#{terms}%", "%#{terms}%")
end
def self.quick_search(terms)
if terms.blank?
Booth.none
else
search(terms)
end
end
def self.available
where(polls: { id: Poll.current_or_recounting }).joins(:polls)
end

View File

@@ -13,7 +13,7 @@ describe Poll::Booth do
expect(booth).not_to be_valid
end
describe "#search" do
describe ".search" do
it "finds booths searching by name or location" do
booth1 = create(:poll_booth, name: "Booth number 1", location: "City center")
booth2 = create(:poll_booth, name: "Central", location: "Town hall")
@@ -22,6 +22,26 @@ describe Poll::Booth do
expect(Poll::Booth.search("hall")).to eq([booth2])
expect(Poll::Booth.search("cen")).to match_array [booth1, booth2]
end
it "returns all booths if search term is blank" do
2.times { create(:poll_booth) }
expect(Poll::Booth.search("").count).to eq 2
end
it "returns all booths if search term is nil" do
2.times { create(:poll_booth) }
expect(Poll::Booth.search(nil).count).to eq 2
end
end
describe ".quick_search" do
it "returns no booths if search term is blank" do
create(:poll_booth)
expect(Poll::Booth.quick_search("")).to be_empty
end
end
describe ".available" do