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的類型?
'def data; HashWithIndifferentAccess.new(超級);如果沒有更好的事情發生,那麼「結束」是一種解決方法。 – 2015-02-23 20:48:10
@ muistooshort放置它的另一種方式是'super.with_indifferent_access'。 – 2015-02-23 20:49:06