在 Rails 中使用 Active Record 时如何指定 Ruby 正则表达式?

要获得所有 invoice_number 是纯数字的工作,我要做的:

To get all jobs which invoice_number is a pure number I do:

Job.where("invoice_number REGEXP '^[[:digit:]]+$'")

是否可以通过在 Ruby 而不是 MySQL 中指定正则表达式来做同样的事情?

Is it possible to do the same by specifying the regex in Ruby rather than MySQL ?

推荐答案

一种方法是

Job.all.select{|j| j =~ /^d+$/}

但它不会像 MySQL 版本那样高效.

but it will not be as efficient as the MySQL version.

另一种可能是使用命名范围来隐藏丑陋的 SQL:

Another possibility is to use a named scope to hide the ugly SQL:

  named_scope :all_digits, lambda { |regex_str|
    { :condition => [" invoice_number REGEXP '?' " , regex_str] }
  }

然后你有Job.all_digits.

请注意,在第二个示例中,您正在为数据库组装查询,因此 regex_str 需要是 MySQL 正则表达式字符串,而不是 Ruby Regex 对象,后者的语法略有不同.

Note that in the second example, you are assembling a query for the database, so regex_str needs to be a MySQL regex string instead of a Ruby Regex object, which has a slightly different syntax.

相关文章