I have a query where I need to add several conditions as an OR
clause, because I want to use LIKE
, so I can not use IN
instead.
So how can I add multiple OR
from an array?
The SQL should look like this:
SELECT * FROM TABLE where a like '%a%' OR a LIKE '%b%' OR a LIKE '%c%' ...
where 'a', 'b', 'c' is from an array.
dataset
.where(column:, Sequel.like(:column, '%#{myarray.first}%'))
myarray.drop(1).each do |v|
dataset.or(Sequel.like(:column, '%#{v}%'))
end
dataset.limit(100)
CodePudding user response:
From the Rails API docs, the .or
conditional query should be chained after a .where
method.
dataset.where(column:, Sequel.like(:column, '%#{myarray.first}%'))
.or(dataset.where(column:, Sequel.like(:column, '%#{myarray.second}%'))
.or(dataset.where(column:, Sequel.like(:column, '%#{myarray.third}%'))
The full answer:
dataset = dataset.where(column:, Sequel.like(:column, '%#{myarray.first}%'))
myarray.drop(1).each do |v|
dataset = dataset.or(dataset.where(column:, Sequel.like(:column, '%#{v}%'))
end
dataset.limit(100)
The same can be achieved without a gem (assuming Sequel.like
is coming from this gem) in "vanilla" Rails.
dataset = dataset.where("column LIKE ?", '%#{myarray.first}%'))
myarray.drop(1).each do |v|
dataset = dataset.or(dataset.where("column LIKE ?", '%#{v}%'))
end
dataset.limit(100)