有没有办法使用HashWithIndifferentAccess序列化ActiveRecord的JSON属性?

the*_*art 4 ruby activerecord json ruby-on-rails

ActiveRecord::ConnectionAdapters::PostgreSQLAdapter在Rails应用程序中使用.假设我有一个架构:

  create_table "foo", id: :bigserial, force: :cascade do |t|
    t.string   "name"
    t.jsonb    "data",              null: false
  end
Run Code Online (Sandbox Code Playgroud)

现在假设我运行以下代码:

class Foo < ActiveRecord::Base
  self.table_name = :foo
end

my_foo = Foo.create!(:name => 'foobar', :data => {:a => 'hello'})
my_foo = Foo.where(:name => 'foobar').first!
puts my_foo.data[:a]
puts my_foo.data['a']
Run Code Online (Sandbox Code Playgroud)

输出将是:

# nil
# 'hello'
Run Code Online (Sandbox Code Playgroud)

是否可以让ActiveRecord使用HashWithIndifferentAccess自动反序列化jsonb类型?

Leo*_*sov 10

| 您可以使用自定义序列化程序,以便您也可以使用符号访问JSON对象.

# app/models/user.rb
class User < ActiveRecord::Base
  serialize :preferences, HashSerializer
end

# app/serializers/hash_serializer.rb
class HashSerializer
  def self.dump(hash)
    hash
  end

  def self.load(hash)
    (hash || {}).with_indifferent_access
  end
end
Run Code Online (Sandbox Code Playgroud)

完全信用 - 没有谷歌搜索 - 转到http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails.

  • 为了在Rails 5中工作,我删除了`.dump`中`hash`的`#to_json`调用. (3认同)

Tom*_*ing 6

如果您的根对象是一个数组,您需要稍微不同地处理它。

轨道 5+

class User < ActiveRecord::Base
  serialize :preferences, HashSerializer
  serialize :some_list, ArrayHashSerializer
end

class HashSerializer
  def self.dump(hash)
    hash
  end

  def self.load(hash)
    (hash || {}).with_indifferent_access
  end
end

class ArrayHashSerializer
  def self.dump(array)
    array
  end

  def self.load(array)
    (array || []).map(&:with_indifferent_access)
  end
end
Run Code Online (Sandbox Code Playgroud)

轨道 <= 4

class User < ActiveRecord::Base
  serialize :preferences, HashSerializer
  serialize :some_list, ArrayHashSerializer
end

class HashSerializer
  def self.dump(hash)
    hash.to_json
  end

  def self.load(hash)
    (hash || {}).with_indifferent_access
  end
end

class ArrayHashSerializer
  def self.dump(array)
    array.to_json
  end

  def self.load(array)
    (array || []).map(&:with_indifferent_access)
  end
end
Run Code Online (Sandbox Code Playgroud)