Administrate::Field::Jsonb
A plugin to show and edit JSON objects within Administrate. inspired by Administrate::Field::JSON.
This gem uses jsoneditor.
Installation
Add this line to your application's Gemfile:
gem 'administrate-field-jsonb'
And then execute:
bundle
Usage
ATTRIBUTE_TYPES = {
# ...
details: Field::JSONB
}.freeze
If you have some kind of serialization, you can call methods on your object with transform option.
ATTRIBUTE_TYPES = {
# ...
details: Field::JSONB.(
transform: %w[to_h symbolize_keys]
)
}.freeze
If you want to edit json displaying on show page, you can use advanced_view option (both JSON and arrays are supported).
ATTRIBUTE_TYPES = {
# ...
details: Field::JSONB.(transform: i[to_h symbolize_keys], advanced_view: {
company: Field::String,
position: Field::String,
skills: Field::JSONB.(advanced_view: {
'name' => Field::String,
'years' => Field::Number.(suffix: ' years')
})
}),
languages: Field::JSONB.(advanced_view: {
'title' => Field::String,
'code' => Field::String,
})
}.freeze
NOTE: don't define advanced_view option if you want to display you JSON with the jsoneditor.
How it looks like
Form
Show
jsoneditor mode
advanced_view mode
advanced_view object
advanced_view array
Recipes
If you want to store your JSON in hash format and not a string add this to your model.
def your_field_name=(value)
self[:your_field_name] = value.is_a?(String) ? JSON.parse(value) : value
end
Example:
def details=(value)
self[:details] = value.is_a?(String) ? JSON.parse(value) : value
end
If you don't see details in advanced_view, try to add this
transform: i[to_h symbolize_keys]
or use string keys.
languages: Field::JSONB.(advanced_view: {
'title' => Field::String,
'code' => Field::String,
})
License
Copyright © 2015-2019 Codica. It is released under the MIT License.
About Codica
Administrate::Field::Jsonb is maintained by Codica. The names and logos for Codica are trademarks of Codica.
We love open source software! See our other projects or hire us to design, develop, and grow your product.