如何使用Rails的活动记录时指定Ruby的正则表达式?如何使用、正则表达式、Rails、Ruby

2023-09-08 18:44:22 作者:smyslenny

要获取所有作业其中 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的正则表达式对象,它代替稍有不同的语法。

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.