Skip to content

Commit

Permalink
Use appropriate LIKE statement in per-model basis. Closes #1676
Browse files Browse the repository at this point in the history
  • Loading branch information
mshibuya committed Jun 25, 2019
1 parent 63b9bff commit 4ea4575
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
11 changes: 8 additions & 3 deletions lib/rails_admin/adapters/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def initialize(scope)

def add(field, value, operator)
field.searchable_columns.flatten.each do |column_infos|
statement, value1, value2 = StatementBuilder.new(column_infos[:column], column_infos[:type], value, operator).to_statement
statement, value1, value2 = StatementBuilder.new(column_infos[:column], column_infos[:type], value, operator, @scope.connection.adapter_name).to_statement
@statements << statement if statement.present?
@values << value1 unless value1.nil?
@values << value2 unless value2.nil?
Expand Down Expand Up @@ -153,10 +153,15 @@ def filter_scope(scope, filters, fields = config.list.fields.select(&:filterable
end

def build_statement(column, type, value, operator)
StatementBuilder.new(column, type, value, operator).to_statement
StatementBuilder.new(column, type, value, operator, model.connection.adapter_name).to_statement
end

class StatementBuilder < RailsAdmin::AbstractModel::StatementBuilder
def initialize(column, type, value, operator, adapter_name)
super column, type, value, operator
@adapter_name = adapter_name
end

protected

def unary_operators
Expand Down Expand Up @@ -269,7 +274,7 @@ def build_statement_for_uuid
end

def ar_adapter
::ActiveRecord::Base.connection.adapter_name.downcase
@adapter_name.downcase
end
end
end
Expand Down
10 changes: 10 additions & 0 deletions spec/rails_admin/adapters/active_record_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,16 @@ def build_statement(type, value, operator)
end
end

it 'chooses like statement in per-model basis' do
connection = double('connection')
allow(FieldTest).to receive(:connection).and_return(connection)

allow(connection).to receive(:adapter_name).and_return('postgresql')
expect(build_statement(:string, 'foo', 'default')).to eq(['(field ILIKE ?)', '%foo%'])
allow(connection).to receive(:adapter_name).and_return('sqlite3')
expect(build_statement(:string, 'foo', 'default')).to eq(['(LOWER(field) LIKE ?)', '%foo%'])
end

it "supports '_blank' operator" do
[['_blank', ''], ['', '_blank']].each do |value, operator|
expect(build_statement(:string, value, operator)).to eq(["(field IS NULL OR field = '')"])
Expand Down

0 comments on commit 4ea4575

Please sign in to comment.