activerecord_json_validator icon indicating copy to clipboard operation
activerecord_json_validator copied to clipboard

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

Open flyingboy007 opened this issue 3 years ago • 3 comments

I have a user model with address field as jsonb column.

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

flyingboy007 avatar Sep 20 '22 14:09 flyingboy007

Hi Abhilash,

While I don’t think it’s possible to generate the address structure from the schema, it’s possible to initialize the address structure by yourself using the after_initialize callback:

class User < ApplicationRecord
  after_initialize do |user|
    # If the address is nil, set it to a blank structure
    user.address ||= { city: nil, postcode: nil }
  end
end

Hope that helps!

remi avatar Sep 20 '22 15:09 remi

@remi I thought we could somehow generate it from the existing JSON structure itself, without hardcoding. But I think it's not possible as of now. Thank you for the support.

flyingboy007 avatar Sep 20 '22 19:09 flyingboy007

I think you could generate it but not via this gem directly. It would potentially be its own gem? 🙂

lake-effect avatar Dec 13 '22 17:12 lake-effect