Search code examples
ruby-on-railsjsonpostgresqlrails-postgresql

Rails dropping last value in array when saving to Postgres database as JSON array


I am building a web app using Rails and Postgres. I am trying to save an array into my database table and it is only deleting the last value in the array.

For example if my array is:

a= [10,12,14,16]

I would do @table.column = a.json

When I do byebug a.json = [10,12,14,16] however if I get the value of @table.column it is equal to [10,12,14]. This happens for all arrays I save to my database.

The column schema is:

t.text "name", default: [], array: true

Screenshot of byebug for my code


Solution

  • Try the serialize instance public method, so in your model do :

    serialize :steves_journey_passed, Array
    

    Then, retry to save your array without .to_json method.

    I hope it helped you !