Browse the Ruby on Rails Community.

You are here: Forums Ask a Rails expert Using like command in RoR...

Replytotopic

Using like command in RoR

Posted in Forums : Ask a Rails expert

 
Profile

Authority 0
Posting Rating 16
Sign in to rate this post

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

 
Me

Authority 37
Posting Rating 100
Sign in to rate this post

Why not just use the prepared statement? Just modify it like this:
:conditions => [ "common_given_names.name LIKE ?", "%#{keyword}%" ]

There are multiple examples in the Rails API documentation, for example here.

HTH

 
Profile

Authority 12
Posting Rating 97
Sign in to rate this post

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

 
Profile

Authority 25
Posting Rating 98
Sign in to rate this post

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.

Replytotopic

Other Recent Topics

Ask a Rails expert : how to write in model

Ask a Rails expert : how to show the params value in page.alert

Ask a Rails expert : Cutomize Will_Paginate next & previouse links

Ask a Rails expert : support AJAX pagination with Will_Paginate plug-in

Ask a Rails expert : Inheritance Determination in View

Ask a Rails expert : Install rails application

Ask a Rails expert : custom sql query

Ask a Rails expert : session handling does not work with REST API

Ask a Rails expert : Display WSDL

Ask a Rails expert : Howto respond a XML error message when there is no @active_record_obj?

Formatting Help
  • *bold*       _italics_      
    bq. (quotes)
  • "DSC":http://www.dsc.net
  • * or # (lists)
or cancel