要获取所有作业其中 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.