I am working with Rails 5 and POSTGRES and need to add an array column. I have seen different syntax to do this.
What is the difference in migrations among..
t.string, :A_options array: true, default: []
and
t.integer, :A_options array: true, default: []
and
t.array, :A_options
Why specify the type as integer or string? How are the first two different than the last?
Also, is there a way to add an array with default:[] using the rails generator?
This creates an array of strings whose default is an empty array:
t.string :A_options, array: true, default: []
This creates an array of integers whose default is an empty array:
t.integer :A_options, array: true, default: []
This should be a NoMethodError:
t.array :A_options
There is no "array" type in PostgreSQL, only "array of X" where "X" is some other column type. PostgreSQL arrays aren't generic containers like Ruby arrays, they're more like arrays in C, C++, Go, ...
If you need a generic container that's more like a Ruby array then perhaps you want jsonb instead. A jsonb array could hold a collection of numbers, strings, booleans, arrays, hashes, ... at the same time.
As far as the generator goes, you can't specify default: [] because you can't specify the default at all:
3.5 Column Modifiers
[...]
nullanddefaultcannot be specified via command line.
Also see Can I pass default value to rails generate migration?.
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