title: Rails Postgres querying array of hash column
body: <p>I have a table with a field of type 'json', which I am using to store array of hashes.</p>
  
  <p>This is my what my schema looks like:</p>
  
  <pre><code>create_table "recommendations", force: true do |t|
      t.text     "message"
      t.json     "vendors",               default: {}
      t.datetime "created_at"
      t.datetime "updated_at"
  end
  </code></pre>
  
  <p>This is my sample data:</p>
  
  <pre><code>&gt;&gt; Recommendation.last.vendors
  [{"name" =&gt; "Alphabeta"}, {"name" =&gt; "Gamma"}]
  </code></pre>
  
  <p>How do I get all the recommendations which includes or has vendor named "Gamma"?</p>
  
  <p>I tried this</p>
  
  <pre><code>&gt;&gt; Recommendation.where("vendors -&gt;&gt; 'name' = 'Gamma'").count
  </code></pre>
  
  <p>but doesn't work.</p>
  
  <p>UPDATE:
  I found a way from answers here <a href="https://stackoverflow.com/questions/19568123/query-for-element-of-array-in-json-column">Query for element of array in JSON column</a></p>
  
  <p>Here it is:</p>
  
  <pre><code>s = "SELECT * FROM recommendations t, json_array_elements(t.vendors) AS elem WHERE  elem-&gt;&gt;'name' = 'Gamma';"
  ActiveRecord::Base.connection.execute(s).to_a
  </code></pre>