Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
flyingboy007 opened this issue Sep 20, 2022 · 3 comments

Comments

@flyingboy007
Copy link

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

@remi
Copy link
Member

remi commented Sep 20, 2022

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!

@flyingboy007
Copy link
Author

flyingboy007 commented Sep 20, 2022

@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.

@lake-effect
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants