3

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?

user2012677
  • 5,465
  • 6
  • 51
  • 113

1 Answers1

6

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?.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • I thought jsonb was for json, so would you need a key value pair. am I wrong? – user2012677 Jan 31 '19 at 19:38
  • You can directly encode an array in JSON, it isn't limited to JavaScript objects or Ruby hashes. You can say `[1, 'a', true].to_json` and get `'[1,"a",true]'` after all. There were issues unpacking JSON-encoded arrays in JavaScript in the past so you'll often see things like `{"0":"x", "1":"y", ...}` instead of a more natural array. – mu is too short Jan 31 '19 at 19:40