0
在ActiveRecord
模型,我試圖動態創建一個查詢具有多個或條件。即:動態查詢多個或條件
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
方法中替換???
來完成這項工作,還是需要採取完全不同的路徑(如我所懷疑的)?