序列化的 json-hash 支持的 ActiveRecord 属性,运行非常流畅
ActiveRecord attributes stored serialized in a json column, super smooth. For Rails 6.0.x through 7.0.x. Ruby 2.7+.
Typed and cast like Active Record. Supporting nested models, dirty tracking, some querying (with postgres jsonb contains), and working smoothy with form builders.
Use your database as a typed object store via ActiveRecord, in the same models right next to ordinary ActiveRecord column-backed attributes and associations. Your json-serialized attr_json attributes use as much of the existing ActiveRecord architecture as we can.
Why might you want or not want this?
Developed for postgres, but most features should work with MySQL json columns too, although has not yet been tested with MySQL.
# migration, default column used is `json_attributes, but this can be changed
class CreatMyModels 12
model.int_array = "12"
model.int_array # => [12]
model.my_datetime = "2016-01-01 17:45"
model.my_datetime # => a Time object representing that, just like AR would cast
model.embedded_lang_and_val = { value: "val"}
model.embedded_lang_and_val #=> #"val"...>You can use ordinary ActiveRecord validation methods with attr_json attributes.
All the attr_json attributes are serialized to json as keys in a hash, in a database jsonb/json column. By default, in a column json_attributes.
If you look at model.json_attributes, you'll see values already cast to their ruby representations.
To see JSON representations, we can use Rails *_before_type_cast methods, *-in_database and [*_for_database] methods (Rails 7.0+ only).
These methods can all be called on the container json_attributes json hash attribute (generally showing serialized JSON to string), or any individual attribute (generally showing in-memory JSON-able object). [This is a bit confusing and possibly not entirely consistent, needs more investigation.]
While the default is to assume you want to serialize in a column called
json_attributes, no worries, of course you can pick whatever named
jsonb column you like, class-wide or per-attribute.
class OtherModel {"__my_string"=>"foo"}
model.save!
model.json_attributes_before_type_cast # => string containing: {"__my_string":"foo"}You can of course combine array, default, store_key, and container_attribute
params however you like, with whatever types you like: symbols resolvable
with ActiveRecord::Type.lookup, or any ActiveModel::Type::Value subclass, built-in or custom.
You can register your custom ActiveModel::Type::Value in a Rails initializer or early on in your app boot sequence:
ActiveRecord::Type.register(:my_type, MyActiveModelTypeSubclass)There is some built-in support for querying using postgres jsonb containment
(@>) operator. (or see here or here). For now you need to additionally include AttrJson::Record::QueryScopes
to get this behavior.
…jsonb_contains will handle any store_key you have set -- you should specify
attribute name, it'll actually query on store_key. And properly handles any
container_attribute -- it'll look in the proper jsonb column.
Anything you can do with jsonb_contains should be handled
by a postgres USING GIN index. Figuring out how to use indexes for jsonb
queries can be confusing, here is a good blog post.
The AttrJson::Model mix-in lets you make ActiveModel::Model objects that can be round-trip serialized to a json hash, and they can be used as types for your top-level AttrJson::Record.
AttrJson::Models can contain other AJ::Models, singly or as arrays, nested as many levels as you like.
That is, you can serialize complex object-oriented graphs of models into a single jsonb column, and get them back as they went in.
AttrJson::Model has an identical attr_json api to
AttrJson::Record, with the exception that container_attribute is not supported.
…You can nest AttrJson::Model objects inside each other, as deeply as you like.
You can edit nested models "in place", they will be properly saved.
m.lang_and_value.lang = "de"
m.save! # no problem!For use with Rails forms, you may want to use attr_json_accepts_nested_attributes_for (like Rails accepts_nested_attributes_for, see doc page on Use with Forms and Form Builders.
If you want to set a default for an AttrJson::Model type, you should use a proc argument for the default, to avoid accidentally re-using a shared global default value, similar to issues people have with ruby Hash default.
attr_json :lang_and_value, LangAndValue.to_type, default: -> { LangAndValue.new(lang: "en", value: "default") }You can also use a Hash value that will be cast to your model, no need for proc argument in this case.
attr_json :lang_and_value, LangAndValue.to_type, default: { lang: "en", value: "default" }There is some support for "polymorphic" attributes that can hetereogenously contain instances of different AttrJson::Model classes, see comment docs at AttrJson::Type::PolymorphicModel.
…GUESS WHAT? You can QUERY nested structures with jsonb_contains,
using a dot-keypath notation, even through arrays as in this case. Your specific
defined attr_json types determine the query and type-casting.
…Remember, we're using a postgres containment (@>) operator, so queries
always mean 'contains' -- the previous query needs a my_labels.hello
which is a hash that includes the key/value, lang: en, it can have
other key/values in it too. String values will need to match exactly.
The main use case of the gem is set up to let you combine multiple primitives and nested models under different keys combined in a single json or jsonb column.
But you may also want to have one AttrJson::Model class that serializes to map one model class, as a hash, to an entire json column on it's own.
AttrJson::Model can supply a simple coder for the ActiveRecord serialization
feature to easily do that.
class MyModel
include AttrJson::Model
attr_json :some_string, :string
attr_json :some_int, :int
end
class MyTable [#, #]If you want to see JSON instead, you could call #as_json on the values. The Rails *_before_type_cast and *-in_database methods may also be useful.
Why might you want this?
You have complicated data, which you want to access in object-oriented fashion, but want to avoid very complicated normalized rdbms schema -- and are willing to trade the powerful complex querying support normalized rdbms schema gives you.
Single-Table Inheritance, with sub-classes that have non-shared data fields. You rather not make all those columns, some of which will then also appear to inapplicable sub-classes. (note you may have trouble with ActiveRecord #becomes in some versions of Rails due to Rails bug. See https://github.com/jrochkind/attr_json/issues/189 and https://github.com/rails/rails/issues/47538))
A "content management system" type project, where you need complex structured data of various types, maybe needs to be vary depending on plugins or configuration, or for different article types -- but doesn't need to be very queryable generally -- or you have means of querying other than a normalized rdbms schema.
You want to version your models, which is tricky with associations between models. Minimize associations by inlining the complex data into one table row.
Generally, we're turning postgres into a simple object-oriented document store. That can be mixed with an rdbms. The very same row in a table in your db can have document-oriented json data and foreign keys and real rdbms associations to other rows. And it all just feels like ActiveRecord, mostly.
Why might you not want this?
An rdbms and SQL is a wonderful thing, if you need sophisticated querying and reporting with reasonable performance, complex data in a single jsonb probably isn't gonna be the best.
This is pretty well-designed code that mostly only uses fairly stable and public Rails API, but there is still some risk of tying your boat to it, it's not Rails itself, and there is some risk it won't keep up with Rails in the future.
When you save a record with any changes to any attr_jsons, it will overwrite the whole json structure in the relevant column for that row. Unlike ordinary AR attributes where updates just touch changed attributes.
Becuase of this, you probably want to seriously consider using ActiveRecord Optimistic Locking to prevent overwriting other updates from processes.
This code is solid and stable and is being used in production. If you don't see a lot of activity, it might be because it's stable, rather than abandoned. Check to see if it's passing/supported on recent Rails? We test on "edge" unreleased rails to try to stay ahead of compatibility, and has worked through multiple major Rails verisons with few if any changes needed.
In order to keep the low-maintenace scenario sustainable, I am very cautious accepting new features, especially if they increase code complexity at all. Even if you have a working PR, I may be reluctant to accept it. I'm prioritizing sustainability and stability over new features, and so far this is working out well. However, discussion is always welcome! Especially when paired with code (failing tests for the bugfix or feature you want are super helpful on their own!).
We are committed to semantic versioning and will endeavor to release no backwards breaking changes without a major version. We are also serious about minimizing backwards incompat releases altogether (ie minimiing major version releases).
Feedback of any kind of very welcome, please feel free to use the issue tracker. It is hard to get a sense of how many people are actually using this, which is helpful both for my own sense of reward and for anyone to get a sense of the size of the userbase -- feel free to say hi and let us know how you are using it!
Except for the jsonb_contains stuff using postgres jsonb contains operator, I don't believe any postgres-specific features are used. It ought to work with MySQL, testing and feedback welcome. (Or a PR to test on MySQL?). My own interest is postgres.
This is still mostly a single-maintainer operation, so has all the sus
暂无开放 Issues,或尚未同步最近议题。