title: Avoiding Potential SQL Injection
body: <p>I am building an API with RoR 4 and PostgreSQL. I want to give my users some search functionality through the index action in my controllers.
  To this end I built the following function.</p>
  <p>query_params is the result of <a href="http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit" rel="nofollow noreferrer">params.permit</a> in one the controllers.</p>
  <p>The ouput of this funcion is then sent to the active record <a href="http://apidock.com/rails/ActiveRecord/QueryMethods/where" rel="nofollow noreferrer">where</a> function.</p>
  <pre><code>def searchable (query_params)
      query = ''    
      query_params.each do |key, value|
        value = value.to_s # Ensure this is a string or you will have crashes below
        # Equals any of multiple values
        if value[/\A(mul-)/]
          value[0..3] = ''
          query += &quot;#{key} IN (#{value}) AND &quot;
        # Not a single value
        elsif value[/\A(&lt;&gt;)/]
          value[0..1] = ''
          query += &quot;(#{key} &lt;&gt; #{value}) AND &quot;    
        # Bigger or smaller than a single value
        elsif value[/\A[&gt;&lt;]/]
          operator = value[/\A[&gt;&lt;]/]
          value[0] = ''
          query += &quot;(#{key} #{operator} #{value}) AND &quot;    
        # Equals a single value
        else
          query += &quot;#{key} = '#{value}' AND &quot;
      
        end
      end
      query = query[0..-5] # removes the last AND
    end
  </code></pre>
  <p>I am worried this method opens my DB up to sql injections. Am I right? If you have an example of a possible injection that would be great. Finally, is there anything I can do to block injections?</p>
  <p>Thanks!</p>