addis_a
November 17, 2014, 6: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…!
barbq
November 18, 2014, 7:44am
2
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”," "] )
barbq
November 18, 2014, 8: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…
barbq
November 18, 2014, 9:15am
4
That wouldn’t catch “hellXXo”…
barbq
November 18, 2014, 8:54am
5
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]
barbq
November 18, 2014, 10:27am
6
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]*/ }