Using Ruby On Rails and the find method with conditions, it is also to possible to use the LIKE statement of SQL without having to escape variables or using raw SQL:
urls = Url.find (:all, :conditions=> ["location like ?", params[:location] + "%"])
In my application, this finds all Url objects with a URL that begins with params[:location]
But this is not the safest solution! The user is able to use its own “%”-characters or the “_” character in the LIKE statement. These are not escaped by rails, so you have to use:
escaped_location = params[:location].gsub ('%', '\%').gsub ('_', '\_') urls = Url.find (:all, :conditions=> ["location like ?", escaped_location + "%"])
More on the need to escape SQL can be found in a railscast.
SQLite3::SQLException error on OS X in a Rails migration
blog comments powered by Disqus