Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails t.array vs t.string array:true, default:[]

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?

like image 239
user2012677 Avatar asked Jul 25 '26 13:07

user2012677


1 Answers

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
[...]

null and default cannot be specified via command line.

Also see Can I pass default value to rails generate migration?.

like image 79
mu is too short Avatar answered Jul 27 '26 03:07

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!