简体   繁体   English

SQL,Rails:检查记录中的JSONB列是否具有键值对

[英]SQL, rails: check if the JSONB column in my record has a key-value pair

No, this is just an example not a dating app for pets. 不,这只是一个例子,并非宠物约会应用。 My app is different and more complex. 我的应用程序与众不同,更加复杂。

I have a rails app. 我有一个Rails应用程序。 I have 2 tables House and Pet. 我有2桌房屋和宠物。 A House has many Pet. 一所房子有很多宠物。 My Pet table has a JSONB column called pet_description that contains a key value pairs of pet type and gender like so: 我的宠物表有一个名为pet_description的JSONB列,其中包含宠物类型和性别的键值对,如下所示:

{ 
  "dog"=>"male", 
  "cat"=>"female", 
  "parrot"=>"male"
}

And the migration file for this is: 迁移文件为:

class AddPetDescriptionToPets < ActiveRecord::Migration
  def change
    add_column :pets, :pet_description, :jsonb, default: {}
    add_index  :pets, :pet_description, using: :gin
  end
end

In my House model, I have a query that executes a SQL query. 在我的房屋模型中,我有一个执行SQL查询的查询。 It works if I do this query to find all houses that have pets. 如果我执行此查询以查找所有有宠物的房屋,它将起作用。

self.where("EXISTS ( SELECT null FROM pets WHERE pets.house_id = houses.id)")

However if I want to query all houses that have a particular pet type and gender then I can't seem to get this query working. 但是,如果我要查询所有具有特定宠物类型和性别的房屋,那么我似乎无法使该查询正常工作。 I am new to JSONB, what am I doing wrong in the query below?, please help!!!! 我是JSONB的新手,在下面的查询中我在做什么错?,请帮忙!!

self.where("EXISTS ( SELECT null FROM pets WHERE pets.house_id = houses.id AND pets.pet_description @> '{'dog' : 'male'}'::jsonb)")

thanks! 谢谢! Greg 格雷格

You may try to use different quotes symbols: 您可以尝试使用不同的引号符号:

self.where("EXISTS ( 
  SELECT null 
  FROM pets 
  WHERE pets.house_id = houses.id 
    AND pets.pet_description @> '{\"dog\" : \"male\"}'::jsonb)")

Or let Rails take care about params formatting: 或者让Rails注意参数格式化:

self.where("EXISTS ( 
  SELECT null 
  FROM pets 
  WHERE pets.house_id = houses.id 
    AND pets.pet_description @> ?)", {dog: 'male'}.to_json)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM