在Rails查询中包含LIKE子句的最佳方法是什么?

Pet*_*xey 22 activerecord ruby-on-rails ruby-on-rails-3

在Rails查询中包含LIKE子句的最佳方法是什么,即(完全不正确的):

 Question.where(:content => 'LIKE %farming%')
Run Code Online (Sandbox Code Playgroud)

Amm*_*mar 42

你会使用以下语法:

Question.where("content LIKE ?" , "%#{farming}%")
Run Code Online (Sandbox Code Playgroud)

  • 你可以这样做:`Question.where("内容LIKE?名字就像?","%#{search1}%","%#{search2}%")` (4认同)
  • 使用此原始SQL只能在SQLite和MySQL上正确地处理不区分大小写的查询.使用Postgres时(例如,在Heroku上),您需要使用ILIKE进行不区分大小写的查询,否则LIKE将区分大小写. (2认同)

num*_*407 33

如果这是Rails 3,你可以使用Arel's matches.这具有与数据库无关的优点.例如:

Question.where(Question.arel_table[:content].matches("%#{string}%"))
Run Code Online (Sandbox Code Playgroud)

这有点笨重,但很容易提取到范围,例如:

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
Run Code Online (Sandbox Code Playgroud)

当然要加入"AND",您可以将范围链接起来.

编辑:+1到metawhere和squeel虽然(没有尝试过后者,但它看起来很酷)他们都添加这种类型的功能和更多.


Mar*_*her 9

如果你想要非常性感的条件并且没有外部依赖性的问题,我强烈推荐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%' }
Run Code Online (Sandbox Code Playgroud)

  • 对于Squeel,正确的语法是`Question.where {content.matches'%farming%'}` (2认同)