11155
(-- --)
November 17, 2014, 5:17pm
1
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
up.
Any ideas? (performance is not important)
Thanks..!
try this
arr = [“XX”,“YY”,“AB”," "]
def self.custom_search(arr = )
query =
arr.each do |term|
query += “title LIKE %#{term}%”
end
where(query.join(" OR "))
end
If you’re using postgres DB
def self.custom_search(arr = )
query =
arr.each do |term|
query += “title ILIKE %#{term}%”
end
where(query.join(" OR "))
end
Paste this method in any model and call it using like this
Post.custom_search([“XX”,“YY”,“AB”," "] )
11155
(-- --)
November 18, 2014, 7:44am
3
Thanks!
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..
Then you can simply use
Post.where(“name ILIKE %?%”, “hello”)
or postgres ( can insensitive )
Post.where(“name ILIKE %?%”, “hello”)
11155
(-- --)
November 18, 2014, 8:15am
5
That wouldn't catch "hellXXo"...
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
Post.all.select{|x| x.title ~= /[hello]*/ }