【发布时间】:2015-04-25 06:53:11
【问题描述】:
我在 Rails 应用程序中使用ActiveRecord::ConnectionAdapters::PostgreSQLAdapter。假设我有一个架构:
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 使用 HashWithIndifferentAccess 自动反序列化 jsonb 类型?
【问题讨论】:
-
如果没有更好的办法,
def data; HashWithIndifferentAccess.new(super); end是一种解决方法。 -
@muistooshort 另一种说法是
super.with_indifferent_access。
标签: ruby-on-rails ruby json activerecord