1

The only way I have been able to do a LIKE query in Rails 2.3 is the following:

access_points.all(:conditions => "mac_address LIKE '%#{@q}%'")

The official documentation says that this way of doing it is insecure because subject to SQL Injection:

Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, Client.first(:conditions => "name LIKE '%#{params[:name]}%'") is not safe. See the next section for the preferred way to handle conditions using an array. http://guides.rubyonrails.org/v2.3.8/active_record_querying.html

But unfortunately it doesn't explain how to do a LIKE query correctly and I haven't been able to find it on google because LIKE is such a general keyword.

Any hint? I am new to Rails but I have experience with Symfony and Django.

nemesisdesign
  • 8,159
  • 12
  • 58
  • 97
  • Use the `?` syntax and put the condition in the array. Searching for "rails 3 like query" returns several hits, including [this SO question](http://stackoverflow.com/questions/4430578/how-to-do-a-like-query-in-arel-and-rails-3) which does precisely that. – Dave Newton Jun 06 '12 at 14:48

2 Answers2

9

This is how you want to do it:

:conditions => ['mac_address LIKE ?', "%#{@q}%"]
Oscar Del Ben
  • 4,485
  • 1
  • 27
  • 41
  • 1
    http://guides.rubyonrails.org/v2.3.8/active_record_querying.html#array-conditions explains that you should NOT use the string escaping on the second part of the array here. That's the part you're trying to avoid with the array syntax. You want `:conditions => ['mac_address LIKE ?', @q]` instead. – joanwolk Oct 24 '12 at 11:51
1

Oscar is correct. Some explanation. You have to use rails sql query filtering as Oscar shows you. So you put the "like ?" in the sql statement and outside that put your search string (with ruby code). Rails will take over and sanitize the search string properly.

Also remember if you are querying Postgres it defaults to case sensitive querying, but there is also a case insensitive ilike too. This has gotten me on a few occasions.

engineerDave
  • 3,887
  • 26
  • 28