Reputation: 1117
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
Reputation: 1307
If you are on PostgreSQL, you may try different solutions, such as:
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"])
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
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