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