How do you declare an array column in Rails?
Detail
I have the following model
rails generate model User address:text   but I want a model which can store multiple addresses per user. The following declaration gives me an error
rails generate model User address[]:text    How do you declare an array column in Rails?
A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With