2

Is there a way to search via Regex pattern in ActiveRecord? I have a collection of products. I'll like to search these products based on their sku column meeting a number of patterns.

SKUs having single letters from [A-Z] should be considered premium products SKUs having single letters [A-Z] and a digit[0-9] should be considered standard products SKUs having double letters and a digit [0-9] should be considered flash products

Here is a pseudo-code of what I need:

product.sku ~= /[A-Z]$/  => Premium Products
product.sku ~= /[A-Z][0-9]$/ => Standard Products
product.sku ~= /[A-Z]{2}[0-9]$/ => Flash products

I don't want to use ruby's select filtering. Is this possible via active-record?

3
  • What database do you use? Postgresql, SQLIite, MySQL? Commented Jan 28, 2020 at 10:24
  • 1
    “Is this possible via active-record?“ — yes, this is possible if you are using the DB that supports fuzzy searches. Commented Jan 28, 2020 at 10:29
  • I'm using postgres as DB Commented Jan 28, 2020 at 10:38

1 Answer 1

4

If you using a database that supports regex matching, this is possible. E.g: Postgres. I have done some regex search on ActiveRecord using Postgres as DB. You can read up this article

So in your case, you can simply do:

premium_products = Product.where("sku ~ ?", '[A-Z]$')
standard_products = Product.where("sku ~ ?", '[A-Z][0-9]$')
flash_products = Product.where("sku ~ ?", '[A-Z]{2}[0-9]$')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.