2016-10-06 2 views
3

일부 정보를 저장하기 위해 Postgres의 JSON 데이터 형식을 사용하고 있습니다. 예를 들어 해시 값으로 JSON 배열에서 해시를 검색하려면 어떻게해야합니까?

은 내가 JSON 문서에 다음과 같은 형식의 (키와 값의 쌍을 포함하는 객체의 배열)을 보유하고 필드 locations와 모델 User 있습니다

[{"name": "Location 1", kind: "house"}, 
{"name": "Location 2", kind: "house"}, 
{"name": "Location 3", kind: "office"}, 
... 
{"name": "Location X", kind: "house"} 
] 

난에 .where으로 조회 할 JSON 데이터 유형.

적어도 하나의 위치가 kind = office 인 사용자를 쿼리하고 싶습니다.

감사합니다.

+1

그것은 당신을 도울 수 있습니다 http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails – Jayaprakash

답변

2

I want to query for users that have locations with kind office

# if locations is jsonb type 
User.where('locations @> ?', { kind: 'office' }.to_json) 
# if locations is json type 
User.where("locations->>'kind' = 'office'") 
# if locations is array of hashes 
User.where('locations @> ?', [{ kind: 'office' }].to_json) 
+0

'@는>''jsonb' 운영자입니다. 불행히도, 나는'json'을 가지고있다. – mamantoha

+0

@mamantoha 님이 혼란에 대한 답변을 편집했습니다. –

+1

시도했지만 작동하지 않았습니다. 항상 빈 결과를 반환합니다. – mamantoha

관련 문제