2015-02-23 77 views
2

我在Rails应用程序中使用ActiveRecord::ConnectionAdapters::PostgreSQLAdapter。假设我有一个模式:有没有办法使用HashWithIndifferentAccess序列化ActiveRecord的JSON属性?

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的自动反序列化jsonb使用HashWithIndifferentAccess的类型?

+1

'def data; HashWithIndifferentAccess.new(超级);如果没有更好的事情发生,那么“结束”是一种解决方法。 – 2015-02-23 20:48:10

+1

@ muistooshort放置它的另一种方式是'super.with_indifferent_access'。 – 2015-02-23 20:49:06

回答

4

|您可以使用自定义序列化程序,以便您可以使用符号访问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.to_json 
    end 

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

完整学分 - sans googling - 去http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails

相关问题