json_attribute is a gem allows Ruby on Rails ActiveRecord model can use one column with jsonb
or json
type to generate many attributes.
in this way, you can store many attributes into one column but manipulating them individually.
Installation
Install
- Add to gem file
gem 'json_attribute'
- Install required gems
$ bundle install
Add json_attribute column to the table of your model
- Create migration
# jsonb is only for PostgresSQL version >= 9.4
$ rails g migration add_json_attribute_to_[table] json_attribute:jsonb
# take json type if your version under 9.4
$ rails g migration add_json_attribute_to_[table] json_attribute:json
- Migrate database
$ rails db:migrate
Add has_json_attribute to your model
- Add to app/models/your_model.rb:
# app/models/your_mode.rb
class YourModel < ActiveRecord::Base
has_json_attribute :attr_1
has_json_attribute :attr_2, default: 'hello'
has_json_attribute :attr_3, type: :string, allow_nil: true
end
- Your model has
attr_1
,attr_2
,attr_3
attributes now. all of them will be save intojson_attribute
column.
has_json_attribute
Options for has_json_attribute attribute_name[, options]
the options as the following:
-
type
validates values must be a certain type before saving. can be:boolean
,:integer
,:float
,:string
. default value:nil
(attribute can be value of any primitive type). -
default
used to set attribute default value. this options can belambda
. for example,default: ->(record) { "#{record.fistr_name} #{record.last_name}" }
. default value:nil
-
presence
validates value must be present. default value:nil
-
column
to determine which table column will be used to provide attributes. default value::json_attribute
-
allow_nil
whentype
is set, this option can allow attribute to benil
.
Examples
class Model < ActiveRecord::Base
has_json_attribute :attr_1
has_json_attribute :attr_2, type: :string, default: 'hello'
has_json_attribute :attr_3, type: :string, default: 'hello', allow_nil: true
has_json_attribute :attr_4, presence: true, default: true
end
# set value
record = Model.new
record.attr_1 = 3.14
record.save!
record.attr_1 # => 3.14
# attribute default value
record = Model.new
record.attr_2 # => 'hello'
# type casting before saving
record = Model.new
record.attr_2 = 123
record.attr_2 # => '123'
# allow nil for attribute with type
record = Model.new
record.attr_3 = nil
record.valid? # => true
# attribute must be present
record = Model.new
record.attr_4 = nil
record.valid? # => false
License
The gem is available as open source under the terms of the MIT License.