views:

274

answers:

3

I'm trying to do a query like this:

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

However, I'm getting a "malformed format string" exception from sanitize_sql, specifying the "%" as the problem.

How can I perform this query?

A: 

Try

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

Just added single quotes around the string %awesome%

Edit: Ok, that doesn;t actually work. The sql sanitizer is doing something screwy with the %s.

This will work.

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

As per John Topley's answer you can make the string a variable if that is what you really need.

One tip I find useful when running into SQL errors is checking the development.log - that will list all the queries that are actually running against the database. Assuming you have basic knowledge of SQL it is often useful to debug them directly in a console, rather than making stabs at the ActiveRecord level (although I think in your case the code was barfing before it got to that stage)

DanSingerman
Adding single quotes doesn't seem to help :-(
kdt
@jcs - what is reported as the SQL statement in the log?
DanSingerman
+6  A: 

Try this syntax:

term = "awesome"
Widget.all(:conditions => ["name LIKE ?", "%#{term}%"])
John Topley
Thank you, that works perfectly. If you happen to have an explanation as to why the version I was trying wasn't working properly then that would be appreciated.
kdt
Rails doesn't parse the SQL in the condition i.e. your percent symbols. You have to pass the parameter into the condition.
John Topley
When you use the syntax above that John suggested, Rails is able to sanitize the input by escaping characters so that users can't do an SQL injection attack. In this process, it surrounds the input with quotes. This is the method you should use to avoid potential problems :-)
Topher Fangio
A: 

Your solution doesn't work because you don't have quotes around %awesome%.

Mike H