How can I use% in argument: conditions for ActiveRecord.find?

I am trying to make a query like this:

Widget.find(:all, :conditions => ["name like %awesome%"])

However, I get an โ€œirregular string formโ€ exception from sanitize_sql, indicating โ€œ%โ€ as the problem.

How to fulfill this request?

+3
source share
3 answers

Try this syntax:

term = "awesome"
Widget.all(:conditions => ["name LIKE ?", "%#{term}%"])
+8
source

Try

Widget.find(:all, :conditions => ["name like '%awesome%'"])

Just added single quotes around the string %awesome%

Edit: Well, that really doesn't work. Sql sanitizer does something sluggish with% s.

This will work.

Widget.find(:all, :conditions => ["name like ?","%awesome%"])

According to John Topley's answer, you can make a string a variable if that is what you really need.

, SQL, development.log -, , . , SQL, , , ActiveRecord ( , barfing , )

0

Your solution does not work because you do not have quotes around% awesome%.

0
source

Source: https://habr.com/ru/post/1709755/


All Articles