title: Rails sanitize user input in active record query
body: <p>Let's say I have following data:</p>
  <p><code>models/supplier.rb</code></p>
  <pre><code>| -- | ---------------- |
  | id | name             |
  | -- | ---------------- |
  | 1  | John Doe's Store |
  | 2  | Jane             |
  | -- | ---------------- | 
  </code></pre>
  <p>I have following queries which are failing to sanitize user's input from search field:</p>
  <pre><code>@term = &quot;John Doe's&quot;
  </code></pre>
  <p><strong>Query 1</strong></p>
  <pre><code>Supplier.order(&quot;case when name LIKE :term 1 else 2 end, name asc&quot;, term: &quot;#{@term}%&quot;)
  
  ArgumentError: Direction &quot;one's%&quot; is invalid. Valid directions are: [:asc, :desc, :ASC, :DESC, &quot;asc&quot;, &quot;desc&quot;, &quot;ASC&quot;, &quot;DESC&quot;]
  from ~/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-4.2.7/lib/active_record/relation/query_methods.rb:1113:in `block (2 levels) in validate_order_args'
  </code></pre>
  <p><strong>Query 2</strong></p>
  <blockquote>
  <p>Vulnerable to SQL Injection attack</p>
  </blockquote>
  <pre><code>Supplier.order(&quot;case when name LIKE '#{@term}%' then 1 else 2 end, name ASC&quot;).first
    
  Supplier Load (2.6ms)  SELECT  &quot;suppliers&quot;.* FROM &quot;suppliers&quot;  ORDER BY case when name LIKE 'John Doe's%' then 1 else 2 end LIMIT 1
  ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near &quot;s&quot;
  LINE 1: ...uppliers&quot;  ORDER BY case when name LIKE 'John Doe's%' then 1..
  </code></pre>
  <p><strong>Query 3</strong></p>
  <blockquote>
  <p>It will success for normal inputs which don't have <code>'</code> (special character) in them, but this query is still vulnerable to SQL injection attack</p>
  </blockquote>
  <pre><code>@term = &quot;John&quot;
  
  Supplier.order(&quot;case when name LIKE '#{@term}%' then 1 else 2 end, name ASC&quot;).first
  
  #&lt;Supplier:0x007fe4bfd8d758
   id: 188,
   name: &quot;John Doe's Store&quot;&gt;
  </code></pre>
  <p>I am not able to figure out a solution for this problem, Please help me complete this query in secure way.</p>