Created
May 29, 2015 12:50
-
-
Save ernie/33f75f2294885b9806f9 to your computer and use it in GitHub Desktop.
Serialization issue with Rails and jsonb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
gem 'activerecord' | |
gem 'minitest' | |
require 'active_record' | |
require 'minitest/autorun' | |
ActiveRecord::Base.establish_connection( | |
adapter: 'postgresql', | |
database: 'playground' | |
) | |
ActiveRecord::Schema.define do | |
create_table :items, :force => true do |t| | |
t.jsonb :data, null: false, default: '[]' | |
end | |
end | |
class Item < ActiveRecord::Base | |
serialize :data, JSON | |
end | |
class SerializationTest < Minitest::Test | |
def item | |
@item ||= Item.new | |
end | |
def test_item_serializes | |
assert_equal [], item.data | |
end | |
end | |
# TypeError: no implicit conversion of Array into String |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For those who might see this later: I know I don't need
serialize
in this simple case. In the real case, I'm serializing/deserializing to an object in my domain model. It's probably worth noting to folks that they will get the deserialized hash/array in their load method if their column type is json/jsonb.It makes sense, if you think in terms of what the adapter delivers being the "serialized" data, but it's not entirely intuitive, either.