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