2

I have a fuzzy search in my rails app, which sql what I want is this:

select * from `user` where name like '%abc%'

I've tried to do it like this:

name = 'abc'
User.where("name like '%?%'", name)

It failed, in console it logged:

select * from `user` where name like '%'abc'%'

Finally I tried this

name = 'abc'
User.where("name like ?", '%' + name + '%')

It worked.

But I think it doesn't like rails way, is there any better way to do that?

ᄂ ᄀ
  • 5,669
  • 6
  • 43
  • 57
worldask
  • 1,837
  • 3
  • 22
  • 37

1 Answers1

1
User.where("name REGEXP ?", 'regex_str')

and regex_str should be MySQL regex string

Try this..

Sonalkumar sute
  • 2,565
  • 2
  • 17
  • 27
  • so find by regexp in database is more better? – Roman Kiselenko Sep 22 '14 at 10:46
  • 3
    Please explain how this code helps to solve the original problem. Also please format (indent) your code blocks to help readability. The goal of the answers are not only to solve the original problem, but to help further readers of this thread understand both the base problem and the solution. Code-only ansers are considered as low quality posts. – Pred Sep 22 '14 at 11:05
  • That's just one line of code, and I edited it. I specified the Rally way to the problem given. I am not sure exactly regexp is better or not. – Sonalkumar sute Sep 22 '14 at 11:23
  • A sidebar comment on this: I think one good reason to use REGEXP over LIKE is that many fuzzy searches are much more complicated that a simple LIKE. In fact, I don't even really think of LIKE as a fuzzy search as much as a substring search. A fuzzy search is much more wide open with scoring applied to results. In some cases the scoring is how many matches were found for a given regex expression in each row. – jaydel May 13 '16 at 14:32