Hello first of all thank you all for the
# avo-2
b
Hello, first of all thank you all for the amazing comunity and the help. I am using a code field to display json data. But everytime I change it the data is saved as string format instead of json format. How should I change the field to parse the text before saving if the field is a code json one
l
hmm. it would seems so
let me think of a solution and push a fix soon (a day or two)
b
Thank you so much
l
can you try something? let's say your field is named
meta
you'd have
field :meta, as: :code
try this
Copy code
ruby
# in your model
def json_meta
  JSON.generate(value)
end

def json_meta=(value)
  self.meta = ActiveSupport::JSON.decode(value)
end

# in your resource use the json_meta property
field :json_meta, as: :code
b
Hi, I will try it
Yes it works
I will include this concern in my models:
Copy code
module AvoJsonFieldAccessorsConcern
  extend ActiveSupport::Concern

  included do    
    attributes = self.columns_hash.select { |_, column| column.type == :jsonb }.keys

    attributes.each do |attribute|
      define_method("json_#{attribute}") do
        JSON.pretty_generate(send(attribute))
      end

      define_method("json_#{attribute}=") do |value|
        send("#{attribute}=", ActiveSupport::JSON.decode(value))
      end
    end
  end
end
and then I will be all set
l
that's cool!