Reputation: 15002
from = [:TPE, :TOKYO, :CHICHAGO]
where(
from: /.*#{from}.*/i,
)
{
from: 'PARIS'
},
{
from: 'PARIS'
},
{
from: 'TOKYO'
},
{
from: 'TPE'
}
{
from: 'TOKYO'
},
{
from: 'TPE'
}
Upvotes: 1
Views: 691
Reputation: 434685
You can use an $in
operator to see if a field matches anything in an array:
where(:from => { :$in => array })
Mongoid patches the MongoDB operators into Symbol
as methods so you could also say:
where(:from.in => array)
If you really are looking for values that contain any of the values in an array then you could just build a single regex that does that using alternation:
re = /#{array.map { |s| Regexp.escape(s.to_s) }.join('|')}/i
Model.where(:from => re)
Note that there's no leading or trailing .*
in the regex as that doesn't do anything useful. Also note the presence of Regexp.escape
calls before the components are joined with the regex alternation operator (|
).
Upvotes: 1