Kocur4d
Kocur4d

Reputation: 6921

Rails NOT IN query and regexp

I have array of strings:

a = ['*@foo.com', '*@bar.com', '*@baz.com']

I would like to query my model so I will get all the records where email isn't in any of above domains.

I could do:

Model.where.not(email: a)

If the list would be a list of strings but the list is more of a regexp.

Upvotes: 2

Views: 53

Answers (2)

tpbowden
tpbowden

Reputation: 2090

It depends on your database adapter. You will probably be able to use raw SQL to write this type of query. For example in postgres you could do:

Model.where("email NOT SIMILAR TO '%@foo.com'")

I'm not saying thats exactly how you should be doing it but it's worth looking up your database's query language and see if anything matches your needs.

In your example you would have to join together your matchers as a single string and interpolate it into the query.

a = ['%@foo.com', '%@bar.com', '%@baz.com']

Model.where("email NOT SIMILAR TO ?", a.join("|"))

Upvotes: 2

Uday kumar das
Uday kumar das

Reputation: 1613

Use this code:

a = ['%@foo.com', '%@bar.com', '%@baz.com']
Model.where.not("email like ?",a.join("|"))

Replace * to % in array.

Upvotes: 0

Related Questions