Sourabh Banka
Sourabh Banka

Reputation: 1117

Rails migration to add a column of type array of objects

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

Upvotes: 1

Views: 4660

Answers (3)

fabOnReact
fabOnReact

Reputation: 5942

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

Upvotes: 2

cnnr
cnnr

Reputation: 1307

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

Upvotes: 2

ashvin
ashvin

Reputation: 2040

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

Upvotes: 2

Related Questions