在 Rails 查询中包含 LIKE 子句的最佳方法是什么? [英] What's the best way to include a LIKE clause in a Rails query?

查看:19
本文介绍了在 Rails 查询中包含 LIKE 子句的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What's the best way to include a LIKE clause in a Rails query i.e. something along the lines of (the completely incorrect):

 Question.where(:content => 'LIKE %farming%')

推荐答案

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

If this is Rails 3 you can use Arel's matches. This has the advantage of being database agnostic. For example:

Question.where(Question.arel_table[:content].matches("%#{string}%"))

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

This is somewhat clunky, but easily extracted to scopes, e.g.:

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",您可以将范围链接起来.

Of course to join with "AND" you could just chain the scopes.

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

+1 to metawhere and squeel though (haven't tried latter but it looks cool) They both add this type of functionality and much more.

这篇关于在 Rails 查询中包含 LIKE 子句的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆