具有多个OR条件的动态查询

时间:2014-02-05 08:32:21

标签: ruby-on-rails arel

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才能使其工作,或者我需要采取完全不同的路径(我怀疑)?

1 个答案:

答案 0 :(得分:2)

这就是我为使其发挥作用所做的事情:

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