Search code examples
ruby-on-rails-4postgresql-9.2pg

Empty strings in postgres string array getting stripped out


Rails 4 with Postgres 9.2. 'pg' gem version 0.16.0.

Model attribute looks like this in schema.rb:

t.string "codes",  array: true

I'm trying to store the following array of strings in this field:

["", "a string"]

In the database table, data for this field is stored as {"","a string"} which is what I expect.

However, in Rails, retrieving this attribute via model.codes strips out the first element in the array and returns just:

["a string"]

a) What happened to the (intentionally-placed) empty string I had in the array?

b) If I replace the empty string, with a single space character, the retrieved attribute looks fine ([" ", "a string"]), but I'm hoping not to have to resort to that.


Solution

  • After much digging, I have something that should be useful for people searching for solutions to the same problem.

    The Postgres adapter in Rails relies on an external gem pg_array_parser for the heavy lifting of efficient array parsing, and defaults processing to it if this gem is available in a project.

    The issue listed above does not recur when adding this gem to my bundle, and all data access/persistence behaves as expected without stripping out empty strings from the array.

    Relevant line in Rails:

    https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/postgresql/array_parser.rb#L18