【问题标题】:Dynamic query with multiple OR conditions具有多个 OR 条件的动态查询
【发布时间】:2014-02-05 08:32:20
【问题描述】:

ActiveRecord 模型上,我正在尝试动态创建具有多个 OR 条件的查询。即:

SELECT * from articles
WHERE (name LIKE '%a%' OR desc LIKE '%a%' OR
       name LIKE '%b%' OR desc LIKE '%b%' OR
       name LIKE '%c%' OR desc LIKE '%c%')

我认为我使用 arel 走在正确的轨道上,但我不知道如何开始查询。

class Article < ActiveRecord::Base

  attr_accessor :title, :text

  def self.search(terms)

    terms = *terms
    t = self.arel_table

    query = terms.reduce(???) do |query, word| 
      search_term = "%#{word}%"
      query.or(t[:title].matches(search_term).or(t[:text].matches(search_term)).expr).expr 
    end

    where(query)
  end

end

我最初是从this answer 那里得到这个想法的,但原来的query 显然是一个字符串,而不是我可以将.or 夹在上面的东西。

我需要在reduce 方法中替换??? 以使其工作,还是我需要采取完全不同的路径(我怀疑)?

【问题讨论】:

    标签: ruby-on-rails arel


    【解决方案1】:

    这是我为使其正常工作所做的:

    class Article < ActiveRecord::Base
    
      attr_accessor :title, :text
    
      def self.search(terms)
        terms = *terms
        t = self.arel_table
    
        # generate array of conditions
        query = terms.collect do |word| 
          search_term = "%#{word}%"
          t[:title].matches(search_term).or(t[:text].matches(search_term)).expr 
        end
    
        # combine conditions
        query = query.reduce {|query, condition| query.or(condition).expr }
    
        where(query)
      end
    
    end
    

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多