Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
J

jsonb_accessor

> 数据库
Open source

Adds typed jsonb backed fields to your ActiveRecord models.

1.1K stars0 likes2 views
WebsiteGitHub

About

Adds typed jsonb backed fields to your ActiveRecord models.

JSONb Accessor

Created by        

Adds typed jsonb backed fields as first class citizens to your ActiveRecord models. This gem is similar in spirit to HstoreAccessor, but the jsonb column in PostgreSQL has a few distinct advantages, mostly around nested documents and support for collections.

It also adds generic scopes for querying jsonb columns.

⚠️ Status

This gem is in maintenance mode and no active development of new features is planned. The major focus is to keep it working with new Ruby/Rails versions and fix any bugs reported. Any PRs for feature requests or enhancements will be reviewed and merged -- so contributions are encouraged!

Table of Contents

  • Installation
  • Usage
  • Scopes
  • Single-Table Inheritance
  • Dependencies
  • Validations
  • Upgrading
  • Development
  • Contributing

Installation

Add this line to your application's Gemfile:

ruby
gem "jsonb_accessor"

And then execute:

$ bundle install

Usage

First we must create a model which has a jsonb column available to store data into it:

ruby
class CreateProducts  "Foo"
product.data #=> { "t" => "Foo" }

You can also pass in a prefix or suffix option.

ruby
class Product  "Foo"
product.external_id_attr #=> 12314122
product.data #=> { "title" => "Foo", "external_id" => 12314122 }

Global Options

You can apply options to all fields by passing an options hash as the second parameter:

ruby
class Product  "Widget"
product.custom_external_id #=> 123
product.product_price #=> 19.99
product.data #=> { "title" => "Widget", "external_id" => 123, "price" => 19.99 }

Global options currently support :prefix and :suffix.

Scopes

Jsonb Accessor provides several scopes to make it easier to query jsonb columns. jsonb_contains, jsonb_number_where, jsonb_time_where, and jsonb_where are available on all ActiveRecord::Base subclasses and don't require that you make use of the jsonb_accessor declaration.

If a class does have a jsonb_accessor declaration, then we define one custom scope. So, let's say we have a class that looks like this:

ruby
class Product `or use plain english if that's what you prefer.

```ruby
Product.all.data_where(price: { : 15 })
Product.all.data_where(price: { >=: 15 })
Product.all.data_where(price: { greater_than: 15 })
Product.all.data_where(price: { greater_than_or_equal_to: 15 })

Product.all.data_where(price: { greater_than: 15, less_than: 30 })

For time related fields you can query using before and after.

ruby
Product.all.data_where(reviewed_at: { before: Time.current.beginning_of_week, after: 4.weeks.ago })

If you want to search for records within a certain time, date, or number range, just pass in the range (Note: this is just shorthand for the above mentioned before/after/less_than/less_than_or_equal_to/greater_than_or_equal_to/etc options).

ruby
Product.all.data_where(price: 10..20)
Product.all.data_where(price: 10...20)
Product.all.data_where(reviewed_at: Time.current..3.days.from_now)

This scope is a convenient wrapper around the jsonb_where scope that saves you from having to convert the given keys to the store keys and from specifying the column.

jsonb_where

Works just like the scope above except that it does not convert the given keys to store keys and you must specify the column name. For example:

ruby
Product.all.jsonb_where(:data, reviewed_at: { before: Time.current }, p: { greater_than: 5 })

# instead of

Product.all.data_where(reviewed_at: { before: Time.current }, price: { greater_than: 5 })

This scope makes use of the jsonb_contains, jsonb_number_where, and jsonb_time_where scopes.

jsonb_where_not

Just the opposite of jsonb_where. Note that this will automatically exclude all records that contain null in their jsonb column (the data column, in the example below).

ruby
Product.all.jsonb_where_not(:data, reviewed_at: { before: Time.current }, p: { greater_than: 5 })

_order

Orders your query according to values in the Jsonb Accessor fields similar to ActiveRecord's order.

ruby
Product.all.data_order(:price)
Product.all.data_order(:price, :reviewed_at)
Product.all.data_order(:price, reviewed_at: :desc)

It will convert your given keys into store keys if necessary.

jsonb_order

Allows you to order by a Jsonb Accessor field.

ruby
Product.all.jsonb_order(:data, :price, :asc)
Product.all.jsonb_order(:data, :price, :desc)

jsonb_contains

Returns all records that contain the given JSON paths.

ruby
Product.all.jsonb_contains(:data, title: "foo")
Product.all.jsonb_contains(:data, reviewed_at: 10.minutes.ago, p: 12) # Using the store key

…

ruby
Product.all.jsonb_excludes(:data, title: "foo")
Product.all.jsonb_excludes(:data, reviewed_at: 10.minutes.ago, p: 12) # Using the store key

jsonb_number_where

Returns all records that match the given criteria.

ruby
Product.all.jsonb_number_where(:data, :price_in_cents, :greater_than, 300)

It supports:

  • >
  • >=
  • greater_than
  • greater_than_or_equal_to
  • `_create_players.rb class CreateVehicles = 3.2 or JRuby >= 9.4
  • Rails >= 6.1
  • PostgreSQL >= 13

JRuby isn't fully supported due to errors, see the CI matrix -- contributions to improve support are welcome!

Development

After checking out the repo, run bin/setup to install dependencies (make sure postgres is running first).

Run bin/console for an interactive prompt that will allow you to experiment.

rake will run Rubocop and the specs.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Add tests and changes (run the tests with rake)
  4. Commit your changes (git commit -am 'Add some feature')
  5. Push to the branch (git push origin my-new-feature)
  6. Create a new Pull Request

Alternatives

  • https://github.com/DmitryTsepelev/store_model
  • https://github.com/palkan/store_attribute ❤️
  • https://github.com/jrochkind/attr_json

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyactiverecordjsonbjsonb-accessorpostgres

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库