Rails (postgres) query with jsonb array

后端 未结 1 501
我寻月下人不归
我寻月下人不归 2020-12-30 13:56

My Product model has a jsonb field specs (which we\'re managing using ActiveRecord\'s store_accessor). Many of my products\' specs have a spec in t

相关标签:
1条回答
  • 2020-12-30 14:03

    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"]';
    

    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) 
    }
    
    0 讨论(0)
提交回复
热议问题