Add an array column in Rails
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
If you are using Postgres, then this post http://blog.plataformatec.com.br/2014/07/rails-4-and-postgresql-arrays/ suggests using array: true
option in migration script:
create_table :users do |t|
# other columns
t.text :addresses, array: true, default: []
end
In case you are not using Postgres, this answer might be helpful: Storing arrays in database : JSON vs. serialized array