2017-09-15 56 views
1

我使用Ruby on Rails和Postgres 9.5。基於jsonb嵌套數據字段查找模型

在數據庫中我有一個表events

我想根據數據字段中的特定值查找所有事件。

events.data具有以下幾種可能的JSON值:

{ 'transition' => { 'from' => 'bacon', 'to' => 'ham' } } 

如何建立一個查詢,將數據=>從過渡bacon =>查找事件?

回答

2

假設你的模式被稱爲Event,你可以做這樣的:

Event.where("data -> 'transition' ->> ? = ?", 'from', 'bacon') 

Here is jsonb operators reference.

這個查詢將返回所有事件,其中data.transition.from等於bacon

擦乾你的查詢,您可以將其添加到存儲庫,如:包含在你的模型

# app/repositories/event_repository.rb 

module EventRepository 
    extend ActiveSupport::Concern 

    included do 
    scope :where_transition, ->(field, value) { where("data -> 'transition' ->> ? = ?", field, value) } 
    end 
end 

後:

include EventRepository 

然後你可以使用它像這樣:

Event.where_transition('from', 'bacon') 
Event.where_transition('to', 'ham')