title: Need to convert a Boolean from Postgres (== String) to a Ruby Boolean
body: <p>I'm using Postgres with Rails. There's a query with a subselect which returns a boolean, but Postgres always returns a String like <code>'t'</code> or <code>'f'</code>. But in the generated JSON I need a real boolean.</p>
  
  <p>This is my query:</p>
  
  <pre><code>SELECT
    *,
    EXISTS (
      SELECT TRUE
      FROM measurement
      JOIN experiment ON measurement.experiment_id = experiment.id
      JOIN location ON experiment.location_id = location.id
      WHERE location.map_id = map.id
      LIMIT 1
    ) AS measurements_exist
  FROM "map"
  </code></pre>
  
  <p>It doesn't matter whether I use <code>THEN true</code> or <code>THEN 1</code> or <code>THEN 'true'</code>, I will always get a string. So my JSON response will always look like that:</p>
  
  <pre><code>[
    {"id":8, ..., "measurements_exist":"f"},
    {"id":9, ..., "measurements_exist":"t"}
  ]
  </code></pre>
  
  <p>But it should(!) look like that:</p>
  
  <pre><code>[
    {"id":8, ..., "measurements_exist":false},
    {"id":9, ..., "measurements_exist":true}
  ]
  </code></pre>
  
  <p>Is there any way to get this working right?</p>
  
  <p>Thank you!</p>
  
  <hr>
  
  <h2>THE SOLUTION:</h2>
  
  <p>Just give the corresponding model (here: <code>Map</code>) an attribute accessor, which uses <code>value_as_boolean</code> to convert the value. So every time the controller tries to access the value, it uses the attribute accessor method automatically.</p>
  
  <p>The controller code:</p>
  
  <pre><code>class MapsController &lt; ApplicationController
    def index
      select = ["*"]
      select.push(measurements_exist) # This will just insert the string returned by the 'measurements_exist' method
      maps = Map.select(select) # Results in 'SELECT *, EXISTS (...) AS measurements_exist FROM "map"'
      render json: maps
    end
  
    private
  
    def measurements_exist
      "EXISTS (
        SELECT TRUE
        FROM measurement
        JOIN experiment ON measurement.experiment_id = experiment.id
        JOIN location ON experiment.location_id = location.id
        WHERE location.map_id = map.id
        LIMIT 1
      ) AS measurements_exist"
    end
  end
  </code></pre>
  
  <p>The model code:</p>
  
  <pre><code>class Map &lt; ActiveRecord::Base
    def measurements_exist
      ActiveRecord::ConnectionAdapters::Column.value_to_boolean(self[:measurements_exist])
    end
  end
  </code></pre>
  
  <p>Resulting JSON:</p>
  
  <pre><code>[
    {"id":7, ..., "measurements_exist":false},
    {"id":6, ..., "measurements_exist":true}
  ]
  </code></pre>