2017-09-15 60 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')