2015-02-23 69 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

相關問題