user3646037
user3646037

Reputation: 293

Add an array column to a resource

I need help going through the steps to add an array column to a resource using the rails g migration command. I have a postgresql database. I need to make an array of strings, and another array of integers. I want it so that in my schema.rb file I have...

create_table "streams", force: true do |t|
t.array   "ids"     #strings
t.array   "lengths" #integers

Upvotes: 2

Views: 2730

Answers (1)

Paritosh Piplewar
Paritosh Piplewar

Reputation: 8122

You have to create new migration so rails g migration change_column_type_of_ids_and_length . Then edit generated migration file.

  1. First try to use change_column method. If this works, your data will be preserved. Else, try step 2

    change_column :streams , :ids , :string , array: true , default: []
    change_column :streams , :lengths, :integer ,array: true , default: []
    
  2. Here we are removing the column so the data , then creating new one.

    remove_column :streams, :ids
    remove_column :streams, :lengths
    add_column :streams , :ids , :string ,array: true , default: []
    add_column :streams , :lengths , :integer ,array:  true , default: []
    

Upvotes: 6

Related Questions