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

前端 未结 3 791
礼貌的吻别
礼貌的吻别 2020-12-16 16:08

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

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

Is it poss

相关标签:
3条回答
  • 2020-12-16 16:25

    Your best bet is either Regexp#tos or Regexp#source or Regexp#inspect.

    But I can't think of why you would want to do this -- Ruby doesn't make it easy to compose Regexps programmatically (which is the only reason I can think of why one might want to compose at one level and submit it to another).

    0 讨论(0)
  • 2020-12-16 16:39

    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.

    0 讨论(0)
  • 2020-12-16 16:40

    we can write like

    scope :only_valid_email_record , :conditions=>["email_id ~ ?","^([a-zA-Z0-9_.'-])+@(([a-zA0-9-])+.)+([a-zA-Z0-9]{2,4})+$"]
    

    It works fine in rails 3.

    0 讨论(0)
提交回复
热议问题