1

I am trying to use regexp to find some results through where clause. But results are coming as expected. Any help will be really appreciated.

username is asha123

Database query

User.where('username  REGEXP ?', /(asha|asha)/) 

Result

User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE (username  REGEXP '--- !ruby/regexp /(asha|asha)/\n...\n')

=> #<ActiveRecord::Relation []> 
1
  • (asha|asha) matches the same rows as simply asha. Commented Mar 22, 2016 at 23:33

1 Answer 1

3

Pass in a string rather than a ruby regular expression.

User.where('username  REGEXP ?', '(asha|asha)') 

Although your database is expecting a "regular expression", ActiveRecord isn't - it just wants to replace your ? with a string value.

Update: to use a variable: just use regular variable interpolation within double quotes. Let's say you had first_name and last_name variables:

User.where('username  REGEXP ?', "(#{first_name}|#{last_name})") 
Sign up to request clarification or add additional context in comments.

2 Comments

Hey thanks Joshua it works :) How can I give variable in same thing like if I have asha in some variable ? How can I pass it then ?
No problem. Consider marking the answer as correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.