tlconnor/activerecord-postgres-array

Append to empty array fails

Opened this issue · 2 comments

>> Request
=> Request(id: integer, inserts: integer_array, updates: integer_array)
>> r = Request.new
=> #<Request id: nil, inserts: [], updates: []>

>> # These array columns have an empty array set as default!

>> r.inserts
=> []

>> # This doesn't work
>> r.inserts << 7
=> [7]
>> r.inserts
=> []

>> # But this does
>> r.inserts += [7]
=> [7]
>> r.inserts
=> [7]

>> # And now, this too
>> r.inserts << 9
=> [7, 9]
>> r.inserts
=> [7, 9]

I basically just do r ||= [] before every insert like so:

r ||= []
r << 7

I basically just do r ||= [] before every insert like so:

r ||= []
r << 7

Tried this and got weird bug that in some cases it didn't work.
When I do:

object.array_attribute = []
object.array_attribute << value

than
object.array_attribute # => [value]

But if I do

object.array_attribute ||= []
object.array_attribute << value

than
object.array_attribute # => []

I think in case of ||= [], object.array_attribute have some value, but it is not the []. IDK, maybe this is some serialization issue.

In the end went with old good

object.array_attribute = object.array_attribute << value