title: Mysterious "ArgumentError: invalid byte sequence in UTF-8" inside scope in Ruby on Rails
body: <p>I've been struggling with this for quite a while and I can't understand the issue. This only happens with a value loaded from the database.</p>
  
  <p>I'm using Rails 4.0.13 and Ruby 2.0.0 by the way, using PostgreSQL</p>
  
  <p>I have the following code:</p>
  
  <pre><code>class Term &lt; ActiveRecord::Base
  end
  
  class Search &lt; ActiveRecord::Base
    scope :filter, -&gt;(params) {
       query = []
       unless params[:term].blank?
         for term in Array(params[:term]) do
           query &lt;&lt; "term = '#{term.gsub('"', '""')}'"
         end
       end
  
       where(query.join(' or '))
    }
  end
  </code></pre>
  
  <p>Then, there's a term called "100%Carbs". If I try to filter by it like this, I get the following error:</p>
  
  <pre><code>term = Term.find 1
  Search.filter(term: term.term)
  
  ArgumentError: invalid byte sequence in UTF-8
  from /home/app/shared/bundle/ruby/2.0.0/gems/activesupport-4.0.13/lib/active_support/core_ext/object/blank.rb:93:in `=~'
  from /home/app/shared/bundle/ruby/2.0.0/gems/activesupport-4.0.13/lib/active_support/core_ext/object/blank.rb:93:in `!~'
  from /home/app/shared/bundle/ruby/2.0.0/gems/activesupport-4.0.13/lib/active_support/core_ext/object/blank.rb:93:in `blank?'
  from /home/app/releases/20160603154616/app/models/search.rb:4:in `block in &lt;class:Search&gt;'
  </code></pre>
  
  <p>But if I write the term on my own, I get a different error:</p>
  
  <pre><code>Search.filter(term: "100%Carbs")
  
  PG::CharacterNotInRepertoire: ERROR:  invalid byte sequence for encoding "UTF8": 0xca 0x72
  : SELECT "search".* FROM "search"  WHERE ((term_store-&gt;'term' = '100�rbs'))
  ActiveRecord::StatementInvalid: PG::CharacterNotInRepertoire: ERROR:  invalid byte sequence for encoding "UTF8": 0xca 0x72
  : SELECT "search".* FROM "search"  WHERE ((term_store-&gt;'term' = '100�rbs'))
  </code></pre>
  
  <p>I've tried a number of combinations of the methods encode and force_encoding, and I always get this error.</p>
  
  <p>The only real difference I noticed between the two attempts is that they have different encoding when they go in the method:</p>
  
  <pre><code>2.0.0 :004 &gt; "100%Carbs".encoding
   =&gt; #&lt;Encoding:ISO-8859-1&gt; 
  2.0.0 :005 &gt; term.term.encoding
   =&gt; #&lt;Encoding:UTF-8&gt; 
  </code></pre>
  
  <p>I really don't understand what's triggering this error, or why the percent character seems to be treated as something else instead of just a character. I've tried to escape it as well, with no success.</p>
  
  <p>I'm really lost here and would appreciate any and all help. Thank you.</p>