有没有一种方法可以使用HashWithIndifferentAccess序列化ActiveRecord的JSON属性? [英] Is there a way to serialize ActiveRecord's JSON properties using HashWithIndifferentAccess?
问题描述
我在Rails应用程序中使用ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
.假设我有一个模式:
I am using ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
in a Rails application. Suppose I have a schema:
create_table "foo", id: :bigserial, force: :cascade do |t|
t.string "name"
t.jsonb "data", null: false
end
现在假设我运行以下代码:
Now suppose I run the following code:
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']
输出为:
# nil
# 'hello'
是否可以要求ActiveRecord使用HashWithIndifferentAccess自动反序列化jsonb类型?
Is it possible to ask ActiveRecord to automatically deserialize jsonb types using HashWithIndifferentAccess?
推荐答案
|您可以使用自定义序列化程序,以便也可以使用符号访问JSON对象.
| You can use a custom serializer so you can access the JSON object with symbols as well.
# 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
全额信用-无广告-转到 http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails .
Full credit - sans googling - goes to http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails.
这篇关于有没有一种方法可以使用HashWithIndifferentAccess序列化ActiveRecord的JSON属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!