1

I’m trying to figure out how to add a new field with a default value into an existing JSON data field for an Active Record model.

The JSON field is called data and has this current structure with these default values.

{“name”: “”, “number”: “”}

The current record in the database looks like this.

{“name”: “first”, “number”: “1111111111”}

I would like to add a new field to the JSON called ”address”.

Now how would I create a rails migration to add this new field to the JSON structure without changing the current values for this record?

I know we can call add_column or change_column but I wasn’t sure how to add the new field without overwriting the exiting values for the record.

Is there a way to do that or do I have to save that data with its current values into a variable, then create a new migration that updates the model to add a new field for the JSON, and finally save the variable from earlier into the record to have its old values in addition to the new field?

Petesta
  • 1,623
  • 3
  • 19
  • 29
  • I just realized I’m using Rails 6.0.3. I’ll update tags. – Petesta Sep 14 '21 at 19:25
  • 2
    The fact that you want to "add a new field with a default" puts the unnecissary JSON anti-pattern stink all over this. If the data has a structure to it such as defined fields create a table instead - the future you will thank you. https://www.2ndquadrant.com/en/blog/postgresql-anti-patterns-unnecessary-jsonhstore-dynamic-columns/ – max Sep 14 '21 at 19:36
  • See https://stackoverflow.com/questions/18209625/how-do-i-modify-fields-inside-the-new-postgresql-json-datatype for how to update an existing object in a Postgres JSON column. This is something you'll have to do with SQL strings in Rails as its DB specific. – max Sep 14 '21 at 19:54

0 Answers0