迁移:
class Preference < ActiveRecord::Migration
def change
enable_extension 'hstore'
create_table :preferences do |t|
t.hstore :prefs
end
end
end
型号:
class Preference < ActiveRecord::Base
store_accessor :prefs
end
如果prefs是一个散列(如{ email:'yes' }
(,这似乎有效,但对于内部有数组的散列({ email:[ 'monday', 'tuesday' ]}
(则无效。
当提取散列时,数组将保存为JSON。
有没有一种好的方法可以将hstore与嵌套哈希和数组一起使用?
我确实尝试将array:true
添加到迁移中,但这似乎只允许保存数组而不是哈希。
如何使用带有嵌套散列和数组的Rails PostgreSQL hstore?
Rails 4.2.4,PostgreSQL 9.3.5
PostgreSQL hstore旨在存储文本字符串的键值对。看看hstore文档。
我使用JSON类型将数组作为值存储在哈希中。有两种JSON数据类型:JSON和JSONB。JSONB支持索引,但速度稍慢,而JSON不支持索引,但是速度更快。您可以在这里阅读它们:JSON类型。
我会做以下事情:
class Preference < ActiveRecord::Migration
def change
create_table :preferences do |t|
t.json :prefs
end
end
end
顺便说一句,在hstore列上设置array: true
意味着您想要存储一个hstore数组。
您可以简单地在访问时解析JSON:
class Preference < ActiveRecord::Base
def prefs
self[:pref] = json_parse_values self[:pref]
end
private
def json_parse_values(hash)
hash.map do |key, val|
begin
[key, (val.is_a?(String) ? JSON.parse(val) : val)]
rescue JSON::ParserError => e
[key, val]
end
end.to_h
end
end
只有当值是字符串时,解析方法才会尝试解析该值。如果它引发一个ParserError
,我们只使用这个字符串。