Skip to content

Commit 41ae027

Browse files
committed
Search in column and global together
1 parent 5806006 commit 41ae027

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

lib/ajax-datatables-rails/orm/active_record.rb

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,20 +30,21 @@ def paginate_records(records)
3030
# ----------------- SEARCH HELPER METHODS --------------------
3131

3232
def build_conditions
33-
if datatable.searchable?
34-
build_conditions_for_datatable
35-
else
36-
build_conditions_for_selected_columns
33+
@criteria ||= begin
34+
criteria = [build_conditions_for_selected_columns]
35+
criteria << build_conditions_for_datatable if datatable.searchable?
36+
criteria.compact.reduce(:and)
3737
end
3838
end
3939

4040
def build_conditions_for_datatable
41+
columns = searchable_columns.reject(&:searched?)
4142
criteria = search_for.inject([]) do |crit, atom|
4243
search = Datatable::SimpleSearch.new(value: atom, regex: datatable.search.regexp?)
43-
crit << searchable_columns.map do |simple_column|
44+
crit << columns.map do |simple_column|
4445
simple_column.search = search
4546
simple_column.search_query
46-
end.reduce(:or)
47+
end.compact.reduce(:or)
4748
end.compact.reduce(:and)
4849
criteria
4950
end

spec/ajax-datatables-rails/orm/active_record_filter_records_spec.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,29 @@
2323
end
2424
end
2525

26+
describe '#build_conditions' do
27+
before(:each) do
28+
create(:user, username: 'johndoe', email: 'johndoe@example.com')
29+
create(:user, username: 'msmith', email: 'mary.smith@example.com')
30+
create(:user, username: 'hsmith', email: 'henry.smith@example.net')
31+
end
32+
33+
context 'with column and global search' do
34+
before(:each) do
35+
datatable.params[:search] = { value: 'example.com', regex: 'false' }
36+
datatable.params[:columns]['0'][:search][:value] = 'smith'
37+
end
38+
39+
it 'return a filtered set of records' do
40+
query = datatable.build_conditions
41+
results = records.where(query).map(&:username)
42+
expect(results).to include('msmith')
43+
expect(results).not_to include('johndoe')
44+
expect(results).not_to include('hsmith')
45+
end
46+
end
47+
end
48+
2649
describe '#build_conditions_for_datatable' do
2750
before(:each) do
2851
create(:user, username: 'johndoe', email: 'johndoe@example.com')

0 commit comments

Comments
 (0)