如何在rails中构建动态作用域

问题描述 投票:0回答:1

如何在给定要排除的可变长度元素数组的情况下构造动态范围搜索,如下所示:

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 的长度可变。

ruby-on-rails arel
1个回答
0
投票

在循环中创建所有条件,然后将它们与

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
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.