Recently I was coding something in Ruby on Rails and I came to a question if I can have array as an attribute for my Model. I started look for Rails documentation and found all available datatypes for Active Records migration
:binary
,:boolean
, :date
, :datetime
, :decimal
,:float
, :integer
, :bigint
, :primary_key
, :references
, :string
, :text
, :time
, :timestamp
I also found that you might use a type that is not in this list as long as it is supported in your database. Database that I primary work with is PostgreSQL. It supports many others data types, like:array
and :hstore
(which is a hash). So yes, we can store multiple values (arrays or hashes) in one column.
Here is how the migration file should look like in order to get attribute as array:
class CreateStore < ActiveRecord::Migration
def change
create_table :stores do |t|
t.string :name
t.string :address, array: true, default: []
t.timestamps
end
end
end
If you want the default value to be an empty array set the default to [], otherwise, the attribute is nil
, until you give it a value.
rails c
> Store.first
> #<Store id: 1, name: "SmartCost", address: ["Location 1", "Location 2"] >