Request json array with active record (Rails 4 / postgresql9.4)

I have a Deal model that has an attribute called "info" with this structure:

Inside the column "transaction information":

Deal1.info = [{"deal_id":"4","text1":"qqq","text2":"sqsq","image1":"sqqs","video1":"sqsq"},{"deal_id":"5","text1":"sqqs","text2":"qq"}] # no image here inside the json Deal2.info = [{"deal_id":"4","text1":"qqq","video1":"sqsq"},{"deal_id":"5","text1":"sqqs","text2":"qq"}] 

The column was defined in mligration as json

 add_column :deals, :info, :json, default: '[]' 

How can I request this in jsonb with active record?

  • find all deals in which the information contains at least one deal_id = 4

  • find the whole deal that contains information that does not contain a json block ({}) with a key called 'image1' (it should only print Deal1, not deal2)

+6
source share
1 answer

I had a similar column, and I had to change the column type from json to jsonb .

add_column :deals, :info, :jsonb, default: [], null: false, index: true

After getting the jsonb data type, I was able to execute this activerecord request type.

Info.where('deals @> ?', '[{"deal_id":"4"}]')

I'm not quite sure how to write all this with activerecord ( http://www.postgresql.org/docs/9.4/static/functions-json.html#FUNCTIONS-JSONB-OP-TABLE ) to reach the 2nd point .

+12
source

All Articles