xin buxu1
xin buxu1

Reputation: 407

write regex query in rails model

I have a model named "SentEmail" and it has attribute named "email_type", some of them start with "email_verification" plus time stamp. For example, it could be like "email_verification_201413423". How could I query all the sent_email with attribute start with "email_verification"? How to write regex to query in rails? This is the query I tried: SentEmail.where('person_id = 1277 AND email_type like "email_verification_%"') but it has syntax error

Upvotes: 1

Views: 142

Answers (4)

Horacio
Horacio

Reputation: 2965

Are you sure that you want to do that with regex?

you can try this

SentEmail.where('email_type like "email_verification_%"')

but if you really need a regexp you could try

SentEmail.where('email_type REGEXP "email_verification*'")

I think that regex should be slower than sql like (obviously if you are working with activerecord and sql).

Upvotes: 2

Beartech
Beartech

Reputation: 6411

And since you asked for Regex specifically:

SentEmail.where("email_type REGEXP ?", 'email_verification.*') #SQLITE with regexp installed?

SentEmail.where("email_type ~* ?", 'email_verification.*') #Postgresql

caveat: this is database dependent. Your DB may or may not support REGEXP and it may use a different syntax.

Upvotes: 0

Beartech
Beartech

Reputation: 6411

Or:

 SentEmail.where('email_type like ?', 'email_verification%' )

Upvotes: 0

vikram7
vikram7

Reputation: 495

This should work:

SentEmail.where('email_type ~* :substring', :substring => "^email_verification")

Upvotes: 1

Related Questions