我在用ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
在 Rails 应用程序中。假设我有一个架构:
create_table "foo", id: :bigserial, force: :cascade do |t|
t.string "name"
t.jsonb "data", null: false
end
现在假设我运行以下代码:
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 使用 HashWithIn DifferentAccess 自动反序列化 jsonb 类型?
|您可以使用自定义序列化程序,以便也可以使用符号访问 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
全部功劳 - 无需谷歌搜索 - 归于http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)