Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Using like command in RoR
3 Posts
Using like command in RoR

I’ve been working on this for a long time. I get this error when trying to work a sql statement like so:

@names = CommonGivenName.find(:all, :conditions => [ “common_given_names.name LIKE

'%#{keyword}%'" ]) I keep getting this error: malformed format string. I couldn’t figure out the problem, but apparently, Rails doesn’t like the % sign. After adding a second one, the query ran just fine. . I just know it works this way.

I tried in this way it is working fine

:conditions => [”common_given_names.name LIKE ?”, “'%#{keyword}%'"]

But I need to construct with out using prepare statement.

Please send mail to me this address

srinivasa_rao3@mindtree.com

Clemens is right.

You should always use a prepared statement, otherwise you are setting yourself up for an SQL injection attack. What would happen if the keyword variable contained "x'; DROP TABLE users; --" ?

Here's a very good resource explaining SQL injection: http://www.unixwiz.net/techtips/sql-injection.html

Both Clemens and Jon give excellent advice. Also, note the '%' wildcard symbols that Clemens added. A LIKE statement is almost worthless without at least wildcarding the front, back or both ends of the search term. If you only needed exact matches then you should always opt for just using a standard '=' on an indexed field since LIKE statements can be a lot more expensive on most databases, causing a full table scan.

3 Posts
Login to add your message