Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

mysql - How to specify Ruby regex when using Active Record in Rails?

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One way is

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

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

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] }
  }

Then you have Job.all_digits.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...