You can use following steps
rails g migration add_subjects_to_book subjects:text
And the migration file:
class AddSubjectsToBook < ActiveRecord::Migration
def change
add_column :books, :subjects, :text, array: true, default: []
end
end
We can check it now:
2.1.2 :001 > b = Book.create
(0.2ms) BEGIN
SQL (2.0ms) INSERT INTO "books" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", "2014-10-17 08:21:17.870437"], ["updated_at", "2014-10-17 08:21:17.870437"]]
(0.5ms) COMMIT
=> #<Book id: "39abef75-56af-4ad5-8065-6b4d58729ee0", title: nil, created_at: "2014-10-17 08:21:17", updated_at: "2014-10-17 08:21:17", description: {}, metadata: {}, subjects: []>
2.1.2 :002 > b.subjects.class
=> Array
If you want to add array while creating table you can do as follows
create_table :products do |t|
t.string :name, null: false
t.references :category, null: false
t.text :tags, array: true, default: []
end
Note: array
column is supported by PostgreSQL
default: []
on them. DON'T do this if you're adding a column to an existing table. You will lock your database down until the migration is finished running. You should instead add the column, populated it, then add the default. We need these three steps for hot compatibility.