How can we initialize the activerecord object with jsonb attributes based on the json structure?

Viewed 23

I have a user model with address field as jsonb column. I am using the gem activerecord_json_validator for validating jsonb schema.

class User < ApplicationRecord
#name :string, age :integer, address :jsonb

  include SchemaStructures
  validates :address, allow_blank: true, json: { message: lambda { |errors|
    errors
  }, schema: JSON_SCHEMA_ADDRESS }


end

Now if I initialize the object it will show the jsonb attribute as nil

User.new()
{name: nil, age: nil, address: nil}

But is it possible to generate the address structure from existing json_schema. so it will show like a normal object but nested like below

{name: nil, age: nil, address: {'city': nil, postcode: nil}}

Thank you

1 Answers

Not sure if it's possible to do this in the model. But you can set defaults for the address jsonb field on the database level. For this try to create a migration:

change_column_default :users, :address, { 'city': nil, postcode: nil }
Related