Advanced string comparison using active record

Hi guys,

I’m looking for a way to pick up database records by comparing my string
to the database record’s string.

The catch is that I have to “clean up” the database strings (not change
the record, just for the purpose of this query).

The basic query is:

Book.where(“title = ?”,”hello”)

And I have an array of substrings e.g.

[“XX”,“YY”,“AB”," "] (the last one is space)

So a record where “hellXX o” or “XX YY hellXX o YY ” would be picked

Any ideas? (performance is not important)


try this

arr = [“XX”,“YY”,“AB”," "]

def self.custom_search(arr = [])
query = []
arr.each do |term|
query += “title LIKE %#{term}%”
where(query.join(" OR "))

If you’re using postgres DB

def self.custom_search(arr = [])
query = []
arr.each do |term|
query += “title ILIKE %#{term}%”
where(query.join(" OR "))

Paste this method in any model and call it using like this

Post.custom_search([“XX”,“YY”,“AB”," "] )


But I might have no been clear, that the string I want to find is
actually “hello”.
The substrings are strings I want to ignore when searching…

That wouldn’t catch “hellXXo”…

Then you can simply use

Post.where(“name ILIKE %?%”, “hello”)

or postgres ( can insensitive )

Post.where(“name ILIKE %?%”, “hello”)

On Tue, Nov 18, 2014 at 12:12 PM, Vivek S.
[email protected]

Hey sorry for misunderstanding it. You will have to use native database
specific regex or pure ruby based expressions and select im a bit bad at
regular expressions but i should look something like this :slight_smile:{|x| x.title ~= /[hello]*/ }

Thanks, I’ll try that.