在 Rails 中使用 Active Record 时如何指定 Ruby 正则表达式? [英] How to specify Ruby regex when using Active Record in Rails?

查看:21
本文介绍了在 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.

这篇关于在 Rails 中使用 Active Record 时如何指定 Ruby 正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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