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 96
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 use mephisto

Ask a Rails expert : How to use mephisto

Ask a Rails expert : will_paginate customization problem

Ask a Rails expert : BackgroundRB still wants 'development' environment...?

Ask a Rails expert : activescaffold, sql exception

Ask a Rails expert : Passing non-english chars in query string

Ask a Rails expert : Rails and 2D barcodes

Ask a Rails expert : apache giving proxy error

Ask a Rails expert : Custom Responses w/ 'extra' information...?

Ask a Rails expert : Log rotation in rails

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