在Rails查询中包含LIKE子句的最佳方法是什么?
在Rails查询中包含LIKE子句的最佳方法是什么,即(完全不正确的):
Question.where(:content => 'LIKE %farming%')
如果这是Rails 3,你可以使用Arel的matches
。 这具有与数据库无关的优点。 例如:
Question.where(Question.arel_table[:content].matches("%#{string}%"))
这有点笨重,但很容易提取到范围,例如:
class Question def self.match_scope_condition(col, query) arel_table[col].matches("%#{query}%") end scope :matching, lambda {|*args| col, opts = args.shift, args.extract_options! op = opts[:operator] || :or where args.flatten.map {|query| match_scope_condition(col, query) }.inject(&op) } scope :matching_content, lambda {|*query| matching(:content, *query) } end Question.matching_content('farming', 'dancing') # farming or dancing Question.matching_content('farming', 'dancing', :operator => :and) # farming and dancing Question.matching(:other_column, 'farming', 'dancing') # same thing for a different col
当然要加入“AND”,您可以将范围链接起来。
编辑:+1到metawhere和squeel虽然(没有尝试过后者,但它看起来很酷)他们都添加这种类型的function和更多。
你会使用以下语法:
Question.where("content LIKE ?" , "%#{farming}%")
如果你想要非常性感的条件,并且没有外部依赖的问题,我强烈推荐MetaWhere ,它的继任者Squeel :
# MetaWhere Question.where(:content.like => '%farming%') # MetaWhere with operators overloaded Question.where(:content =~ '%farming%') # Squeel Question.where { :content.matches => '%farming%' } # Squeel with operators overloaded Question.where { :content =~ '%farming%' }