1

I would like to add a column of type Array of Objects.

 "users_to_employer":[
     {
       key1 : value,
       key2 : value,
     },
     {
       key1: value,
       key2: value,
     }
  ]

I am stuck in migration.

add_column :table_name, :column_name, ......

What to write in place of ......

3
  • which data base you are using? postgres, mysql or mongodb? Commented May 24, 2019 at 8:05
  • @G.B using postgres database Commented May 24, 2019 at 8:12
  • @ashvin has answered which seems legit. You can also have a look on hstore for postgres which stores hashes Commented May 24, 2019 at 8:14

3 Answers 3

2

Add a column with datatype text

add_column :table_name, :column_name, :text, default: "" #Field type should be text to store array of hashes

In your model serialize it to convert it into array

class TableName < ActiveRecord::Base
  serialize :column_name, Array
end

Hope this will help you

Sign up to request clarification or add additional context in comments.

Comments

2

If you are on PostgreSQL, you may try different solutions, such as:

  1. Array column type
    
    create_table :table_name do |t|
      ...
      t.string 'array_column_name', array: true
      ...
    end

    add_index :table_name, :array_column_name, using: 'gin'


    # Usage
    YourModel.create(array_column_name: ["value1", "value2"])
  1. Or you can try to store your data as JSON
    create_table :table_name do |t|
      t.json 'json_column_name'
    end

    # Usage
    YoutModel.create(json_column_name: { key1: "val1", key2: ["val21", "val22"]})

and parse your json more flexible, to array and other structures.

More information you can see at official Rails documentation

Comments

2
add_column :table_name, :column_name, :string, array: true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.