且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有jsonb数组的Rails(postgres)查询

更新时间:2023-02-05 15:37:42

您要使用的是

What you want to use is the @> operator, which tests whether your left-hand value contains the right-hand value. "Contains" works for both objects and arrays, so the following query would work:

SELECT * FROM products WHERE specs->'spec_options' @> '["spec1", "spec2"]';

我相信您可以将其转换为ActiveRecord兼容的语法,如下所示:

Which I believe you can transform into ActiveRecord-compatible syntax like so:

scope :with_spec_options, ->(spec_options) { 
  where("specs->'spec_option' @> ?", spec_options.to_json) 
}