如何在给定要排除的可变长度元素数组的情况下构造动态范围搜索,如下所示:
class Participant < ApplicationRecord
scope exclude_names, -> (['%name1%', '%name2%', '%name3%', ...]) {
where.not(Participant.arel_table[:name_search].matches('%name1%').or(
Participant.arel_table[:name_search].matches('%name2%').or(
Participant.arel_table[:name_search].matches('%name3%').or(
...
}
但动态完成,因为 name_list 的长度可变。
在循环中创建所有条件,然后将它们与
or
-s 组合到您的条件中。
scope :exclude_names, -> (names) do
clauses = names.map do |name|
Participant.arel_table[:name_search].matches(name)
end
condition = clauses.inject(:or)
where.not(condition)
end