Reputation: 23
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?
Upvotes: 2
Views: 1323
Reputation: 1776
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]$')
Upvotes: 4