How can we initialize the activerecord object with jsonb attributes based on the json structure?
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
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 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.
I think you could generate it but not via this gem directly. It would potentially be its own gem? 🙂